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
  • 52,309
  • 8
  • 74
  • 127
Trip
  • 26,093
  • 43
  • 151
  • 267
  • 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,508
  • 2
  • 58
  • 60
3

How about Array.slice?

var firstThree = myArray.slice(0, 3);
rjz
  • 15,582
  • 3
  • 33
  • 34
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
  • 38,150
  • 11
  • 77
  • 129
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
  • 572,313
  • 128
  • 898
  • 1,281
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,378
  • 5
  • 33
  • 44