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.

simbabque
  • 53,749
  • 8
  • 73
  • 136
Trip
  • 26,756
  • 46
  • 158
  • 277
  • Please refer to similar question http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value – adamb Nov 01 '12 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? – rafaelbiten Nov 01 '12 at 16:03

5 Answers5

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"]
Kyle
  • 21,978
  • 2
  • 60
  • 61
3

How about Array.slice?

var firstThree = myArray.slice(0, 3);
rjz
  • 16,182
  • 3
  • 36
  • 35
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.

Joe Enos
  • 39,478
  • 11
  • 80
  • 136
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"]
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
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"]
Dinesh P.R.
  • 6,936
  • 6
  • 35
  • 44