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
  • 50,588
  • 8
  • 69
  • 121
Trip
  • 25,831
  • 41
  • 146
  • 260
  • 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,078
  • 2
  • 56
  • 60
3

How about Array.slice?

var firstThree = myArray.slice(0, 3);
rjz
  • 15,222
  • 3
  • 30
  • 33
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
  • 36,707
  • 11
  • 72
  • 128
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
  • 513,640
  • 108
  • 821
  • 1,164
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.
  • 5,870
  • 5
  • 32
  • 44