Categories
JavaScript Answers

How to get the last 5 elements, excluding the first element from an array with JavaScript?

Spread the love

To get the last 5 elements, excluding the first element from an array with JavaScript, we call the Math.max and slice methods.

For instance, we write

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

to call Math.max with arr.length - 5 and 0 to return the max number between the 2 numbers.

And then we call slice to return an array with the arr entries between the index returned by max to the last element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *