slice array from N to last element

Javascript

Javascript Problem Overview


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)  // []

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

["a","b","c","d","e"].slice(-3) => ["c","d","e"]

Solution 5 - Javascript

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']

Solution 6 - Javascript

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);
}

Solution 7 - Javascript

var arr = ["a", "b", "c", "d", "e"];
arr.splice(0,2);
console.log(arr);

Please use above code. May be this you need.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionevfwcqcgView Question on Stackoverflow
Solution 1 - JavascriptTim S.View Answer on Stackoverflow
Solution 2 - JavascriptConnor GoddardView Answer on Stackoverflow
Solution 3 - JavascriptinsomiacView Answer on Stackoverflow
Solution 4 - JavascriptSekhar552View Answer on Stackoverflow
Solution 5 - JavascriptjayvatarView Answer on Stackoverflow
Solution 6 - Javascriptuser13898356View Answer on Stackoverflow
Solution 7 - JavascriptAlok RanjanView Answer on Stackoverflow