How do I get the last 5 elements, excluding the first element from an array?

Viewed 246388

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

[1, 55, 77, 88] // ...would return [55, 77, 88]

adding additional examples:

[1, 55, 77, 88, 99, 22, 33, 44] // ...would return [88, 99, 22, 33, 44]

[1] // ...would return []
9 Answers

ES6 way:

I use destructuring assignment for array to get first and remaining rest elements and then I'll take last five of the rest with slice method:

const cutOffFirstAndLastFive = (array) => {
  const [first, ...rest] = array;
  return rest.slice(-5);
}

cutOffFirstAndLastFive([1, 55, 77, 88]);

console.log(
  'Tests:',
  JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88])),
  JSON.stringify(cutOffFirstAndLastFive([1, 55, 77, 88, 99, 22, 33, 44])),
  JSON.stringify(cutOffFirstAndLastFive([1]))
);

You can do it in one line like this:

const y = [1,2,3,4,5,6,7,8,9,10];
const lastX = 5;
const res = y.filter((val, index, arr) => index > arr.length - lastX - 1);
    
console.log(res);

.filter((val, index, arr) => index > arr.length - 6)

Beginner solution:

var givme = function(n) {
    if(n.length == 1) {
        return [];
    }
    if(n.length > 5) {
        return n.slice(n.length-5, n.length);
    }
    if(n.length <= 5) {
       return n.slice(1, n.length);
    }
}

// console.log(givme([1, 55, 77, 88, 99, 22, 33, 44]));
array.reverse()
     .slice(0,5)
     .reverse()  //if you wanna keep the order of last 5

const myOriginalArray = [...Array(10).keys()] //making an array of numbers

const instanceFromlastFiveItemsOfMyArray = [
    ...myOriginalArray.reverse().slice(0,5).reverse()
    ]
Related