76

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)  // []
evfwcqcg
  • 15,755
  • 15
  • 55
  • 72

7 Answers7

152

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.

Tim S.
  • 13,597
  • 7
  • 46
  • 72
  • ok... but what if I can not predict if the end of the slice will be defined or not. In python we have str[start:None] to slice to the end. How can I equivalently do it on javascript ? – yota Mar 31 '16 at 09:09
  • @yota If you know the length of the array you can pass that as second argument: `arr.slice(2, arr.length)`. If the second argument exceeds the array length, it’ll still return `begin` until the end of the sequence. If that’s not working for you, you will need an if-statement. – Tim S. Apr 03 '16 at 21:55
10

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.

Connor Goddard
  • 635
  • 7
  • 14
5

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"]
insomiac
  • 5,648
  • 8
  • 45
  • 73
4
["a","b","c","d","e"].slice(-3) => ["c","d","e"]
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Sekhar552
  • 51
  • 2
1

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']
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
jayvatar
  • 199
  • 2
  • 9
1

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

var arr = ["a", "b", "c", "d", "e"];
arr.splice(0,2);
console.log(arr);
Please use above code. May be this you need.
Alok Ranjan
  • 967
  • 10
  • 10