Borislav Hadzhiev
Tue Oct 05 2021·2 min read
Photo by Tim Trad
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.
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.
-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.
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.
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.
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.