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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28279{{"`Drop Array Elements From the Left`"}} javascript/data_types -.-> lab-28279{{"`Drop Array Elements From the Left`"}} javascript/arith_ops -.-> lab-28279{{"`Drop Array Elements From the Left`"}} javascript/comp_ops -.-> lab-28279{{"`Drop Array Elements From the Left`"}} end

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.

Other JavaScript Tutorials you may like