Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a javascript array, how do I get the last 5 elements, excluding the first element?

People also ask

How do I find the last 5 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array. Copied!

How do you find an array without the first element?

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

How do you get all the elements of an array except first?

You can use array. slice(0,1) // First index is removed and array is returned. FIrst index is not removed, a copy is created without the first element.


You can call:

arr.slice(Math.max(arr.length - 5, 1))

If you don't want to exclude the first element, use

arr.slice(Math.max(arr.length - 5, 0))

Here is one I haven't seen that's even shorter

arr.slice(1).slice(-5)

Run the code snippet below for proof of it doing what you want

var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],
  arr2 = [0, 1, 2, 3];

document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '<br/>ARRAY 2: ' + arr2.slice(1).slice(-5);

Another way to do it would be using lodash https://lodash.com/docs#rest - that is of course if you don't mind having to load a huge javascript minified file if your trying to do it from your browser.

_.slice(_.rest(arr), -5)


If you are using lodash, its even simpler with takeRight.

_.takeRight(arr, 5);


var y = [1,2,3,4,5,6,7,8,9,10];

console.log(y.slice((y.length - 5), y.length))

you can do this!