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.
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.
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"]
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"]
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"]