How to get Last X Elements of an Array in JavaScript
Table of Contents
While working with arrays in JavaScript, you may want to get the last X elements in an array.
A common use case is when you recently pushed some items onto an array, and you want to get back the latest X items.
In this post, we'll learn how to get the last X elements in an array in JavaScript.
Getting the last X elements in an array
Let's first start with an example array:
JAVASCRIPTconst array = ["apple", "banana", "orange", "pear", "plum"];
We can access the last X elements in this array by using the built-in slice()
method.
JAVASCRIPTconst array = ["apple", "banana", "orange", "pear", "plum"];
const lastXElements = array.slice(-x);
For example, if you want the last 2 elements in the array, you can use the following code:
JAVASCRIPTconst array = ["apple", "banana", "orange", "pear", "plum"];
const last2Elements = array.slice(-2);
console.log(last2Elements);
BASH(2) ['pear', 'plum']
0: "pear"
1: "plum"
length: 2
Usually, the splice
method is used with a positive value, but when you pass it a negative value, it will start from the last element in the array, which is what we want in this case.
Conclusion
In this post, we learned how to get the last X elements in an array in JavaScript.
You can just call the slice
method with a negative value so that it will start from the last element in the array and therefore return the desired elements.
Hope this post has been useful to you. Happy coding!
- Getting Started with TypeScript
- Create an RSS Reader in Node
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript