Get the last N number of elements from an array in JavaScript
Today we’ll show you how to get the last N number of elements from an array in JavaScript. There are multiple ways to get last N number of items from an array using JavaScript.
In the previous article, we explained to you how to get the first N number of elements from an array. You may check the few more articles related to the Array.
Ways to get the last N number of elements from an array
1. slice() method
In this method, we will use the slice() method to get the last 5 items from an array. It is a very simple and most preferable method to get the last 5 elements from the list.
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
Using the splice() method, we can also get the last N number of elements from the list. But it will update the original array by removing the last N number of elements 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..!! 🙂