How to get last N elements of an array in JavaScript
Today We’ll teach you how to retrieve the last N elements from an array in JavaScript today. Using JavaScript, there are several ways to extract the last N number of elements from an array.
We showed you how to get the first N number of elements from an array in the previous post. You may read a couple more articles on the Array.
Ways to get last N elements of an array
1. slice() method
We’ll use the slice() function to obtain the last 5 elements from an array in this method. To get the last 5 entries from the list, this is a very easy and preferred approach.
Example 1: Get the last 5 elements
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// get the last 5 elements
const n = 5;
const newArr = arr.splice(-n);
console.log(newArr);
// [6, 7, 8, 9, 10]
Example 2: Get the last 2 elements
const arr = [
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
},
{
userId: 2,
id: 2,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 3,
title: "fugiat veniam minus",
completed: false
}
];
const n = 2;
const newArr = arr.splice(-n);
console.log(newArr);
/*
[
{
userId: 2,
id: 2,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 3,
title: "fugiat veniam minus",
completed: false
}
]
*/
2. splice() method
We can also retrieve the last N number of entries from the list using the splice() method. However, the original array will be updated by eliminating the last N entries from the list.
Example 1: Get the last 5 elements and update original list
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// get the last 5 elements
const n = 5;
const newArr = arr.splice(-n);
console.log(newArr);
// [6, 7, 8, 9, 10]
console.log(arr);
// [1, 2, 3, 4, 5]
Example 2: Get the last 2 elements and update original list
const arr = [
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
},
{
userId: 2,
id: 2,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 3,
title: "fugiat veniam minus",
completed: false
}
];
const n = 2;
const newArr = arr.splice(-n);
console.log(newArr);
/*
[
{
userId: 2,
id: 2,
title: "quis ut nam facilis et officia qui",
completed: false
},
{
userId: 1,
id: 3,
title: "fugiat veniam minus",
completed: false
}
]*/
console.log(arr);
/*
[
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
}
]
*/
That’s it for today.
Thank you for reading. Happy Coding..!!