How to make this transformation?
["a","b","c","d","e"] // => ["c", "d", "e"]
I was thinking that slice
can do this, but..
["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ]
["a","b","c","d","e"].slice(2,0) // []
How to make this transformation?
["a","b","c","d","e"] // => ["c", "d", "e"]
I was thinking that slice
can do this, but..
["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ]
["a","b","c","d","e"].slice(2,0) // []
Don't use the second argument:
Array.slice(2);
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
If end is omitted, slice extracts to the end of the sequence.
An important consideration relating to the answer by @insomniac is that splice
and slice
are two completely different functions, with the main difference being:
splice
manipulates the original array.slice
returns a sub-set of the original array, with the original array remaining untouched. See: http://ariya.ofilabs.com/2014/02/javascript-array-slice-vs-splice.html for more information.
Just give the starting index as you want rest of the data from the array..
["a","b","c","d","e"].splice(2) => ["c", "d", "e"]
["a","b","c","d","e"].slice(-3) => ["c","d","e"]
Slice ends at the specified end argument but does not include it. If you want to include it you have to specify the last index as the length of the array (5 in this case) as opposed to the end index (-1) etc.
["a","b","c","d","e"].slice(2,5)
// = ['c','d','e']
You must add a "-" before n If the index is negative, the end indicates an offset from the end.
function getTail(arr, n) {
return arr.slice(-n);
}
var arr = ["a", "b", "c", "d", "e"];
arr.splice(0,2);
console.log(arr);