Introduction
In this lab, we will explore how to drop array elements from the right using JavaScript. We will create a function that takes an array and a number as arguments and returns a new array with the specified number of elements removed from the right. We will use the Array.prototype.slice() method to achieve this functionality and also learn how to set a default value for the second argument of the function.
Drop Array Elements From the Right
To remove a specified number of elements from the right of an array, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.slice()to remove the specified number of elements from the right. - If you want to remove only one element, you can omit the last argument,
n, and the default value of1will be used.
Here's an example code snippet:
const dropRight = (arr, n = 1) => arr.slice(0, -n);
You can test this function with the following examples:
dropRight([1, 2, 3]); // [1, 2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []
Summary
Congratulations! You have completed the Drop Array Elements From the Right lab. You can practice more labs in LabEx to improve your skills.