Get the last N elements of an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the last N 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.

index.js
const arr = ['a', 'b', 'c', 'd', 'e']; const last3 = arr.slice(-3); // 👉️ ['c', 'd', 'e'] console.log(last3); const last2 = arr.slice(-2); // 👉️ ['d', 'e'] console.log(last2);

The only parameter we passed to the Array.slice method is the start index.

Passing a negative index indicates an offset from the end of the array. A negative index of -3 means give me the last 3 elements of the array.

This is the same as passing array.length - 3 as an argument to the slice() method.

index.js
const arr = ['a', 'b', 'c', 'd', 'e']; const last3 = arr.slice(-3); console.log(last3); // 👉️ ['c', 'd', 'e'] const last3Again = arr.slice(arr.length - 3); console.log(last3Again); // 👉️ ['c', 'd', 'e']

Either way, we tell the slice method to copy the last 3 elements of the array and place them in a new array.

The Array.slice method does not mutate the original array. Instead, it returns a new array with the copied elements (a shallow copy of a portion of the original array).

Even if we try to get more elements than the array contains, Array.slice won't throw an error. Instead, it returns a new array with all elements.

index.js
const arr = ['a', 'b', 'c']; const last100 = arr.slice(-100); console.log(last100); // 👉️ ['a', 'b', 'c']

We tried to get the last 100 elements of an array which only contains 3 elements.

In this case all elements get copied to the new array.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.