Get the last N elements from an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

banner

Photo by Tim Trad

Get the last N elements from an Array #

To get the last N elements from 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 from 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 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, 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']

In the example 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee