Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slice array from N to last element

Tags:

javascript

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)  // [] 
like image 692
evfwcqcg Avatar asked Jan 18 '13 08:01

evfwcqcg


People also ask

How do you find the last two elements of an array?

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.

How do you get the last element of slice in go?

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.

How do you slice elements in an array?

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.

How do you slice an array at the end?

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.


2 Answers

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.

like image 89
Tim S. Avatar answered Sep 26 '22 08:09

Tim S.


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.

like image 40
Connor Goddard Avatar answered Sep 24 '22 08:09

Connor Goddard