0

I have an array like:

["a", "b", "c", "d", "e"]

Now I want to just have the first 3 items. How would I remove the last two dynamically so that I could also have a 20 letter array, but reduce that down to the first 3 as well.

2
  • Please refer to similar question stackoverflow.com/questions/3954438/… Commented Nov 1, 2012 at 16:03
  • What if you construct another array with the first three elements and than exclude that original array, if you don't need it anymore? Commented Nov 1, 2012 at 16:03

5 Answers 5

5
var a = ["a", "b", "c", "d", "e"];
a.slice(0, 3); // ["a", "b", "c"]

var b = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
b.slice(0, 3); // ["a", "b", "c"]
Sign up to request clarification or add additional context in comments.

Comments

3

How about Array.slice?

var firstThree = myArray.slice(0, 3);

Comments

2

The splice function seems to be what you're after. You could do something like:

myArray.splice(3);

This will remove all items after the third one.

Comments

2

To extract the first three values, use slice:

var my_arr = ["a", "b", "c", "d", "e"];
var new_arr = my_arr.slice(0, 3); // ["a", "b", "c"]

To remove the last values, use splice:

var removed = my_arr.splice(3, my_arr.length-3); // second parameter not required
// my_arr == ["a", "b", "c"]

Comments

0

In underscore.js we can use the first function

_.first(array, [n]) Alias: head

Returns the first element of an array. Passing n will return the first n elements of the array.

_.first(["a", "b", "c", "d", "e"],3);
=> ["a", "b", "c"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.