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) // []
To access the last n elements of an array, we can use the built-in slice() method by passing -n as an argument to it. n is the number of elements, - is used to access the elements at end of an array.
Use the index len(a)-1 to access the last element of a slice or array a . Go doesn't have negative indexing like Python does.
JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end ( end not included) where start and end represent the index of items in that array. The original array will not be modified.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With