Get last n items from an array in JavaScript

I am again here with a new JavaScript solution. In this tutorial, you are going to learn how to get last n items from an array in JavaScript programming.

For example, suppose you have an array that is given below:

[235, 585, 985, 36, 452, 231]

Now you want to get the last three items from the array. You can see that the last three items are 36, 452 and 231. So how can we do it programmatically?

Here I am going to give you a simple trick to achieve this task.

JavaScript already has the array method slice(). This method can return selected elements from a given array and then return a new array that only contains the selected method.

All we need to do is just to provide an integer argument which will be the starting point of the array. Well, the argument also can be a negative integer.

Using the negative integer as the argument for the array slice() method is the trick that will able to return the last n items of a JavaScript array.

See the example below:

var jsArr = [235, 585, 985, 36, 452, 231];
console.log(jsArr.slice(-1)); // Output: [231]
console.log(jsArr.slice(-2)); // Output: [452, 231]
console.log(jsArr.slice(-3)); // Output: [36, 452, 231]

In the above example, you can see that we are able to get last n items from an array in JavaScript using the array slice() method.

So simple and easy. Isn’t it…

Also, read:

Here in our example when we use slice(-1) it is returning the last item from the array. If we are using slice(-3) it is returning the last 3 items from our array.

I hope, you have understood how the array slice method working with a negative integer type parameter and how it is returning the last n items from our array.

Leave a Reply

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