Drop Array Elements From the Left

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to create a new array by dropping elements from the left of an existing array using JavaScript. We will learn how to use the Array.prototype.slice() method to remove a specified number of elements from the left of an array and how to set a default value for the number of elements to remove. By the end of this lab, you will have a better understanding of how to manipulate arrays in JavaScript.

Removing Array Elements From the Left

To start practicing coding, open the Terminal/SSH and type node.

Here's a function that creates a new array with a specified number of elements removed from the left:

const drop = (arr, n = 1) => arr.slice(n);

The function uses Array.prototype.slice() to remove the specified number of elements from the left. If you omit the last argument, n, the function will use a default value of 1.

Here are some examples of using the drop function:

drop([1, 2, 3]); // [2, 3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []

Summary

Congratulations! You have completed the Drop Array Elements From the Left lab. You can practice more labs in LabEx to improve your skills.