Introduction
In this lab, we will explore the lastN function which is used to extract the last n elements of an array. We will learn how to use the Array.prototype.slice() method to achieve this and see how it can be implemented in our JavaScript programs. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript and extract specific elements from them.
How to Get Last N Elements of an Array in JavaScript
To get the last n elements of an array in JavaScript, follow these steps:
Open the Terminal/SSH and type
nodeto start practicing coding.Use
Array.prototype.slice()with a start value of-nto get the lastnelements of the array.
Here's the JavaScript code to get the last n elements of an array:
const lastN = (arr, n) => arr.slice(-n);
To test the code, call the lastN() function with the array and the number of elements you want to get, like this:
lastN(["a", "b", "c", "d"], 2); // ['c', 'd']
Summary
Congratulations! You have completed the Last N Elements lab. You can practice more labs in LabEx to improve your skills.