Drop Array Elements From the Right

JavaScriptJavaScriptBeginner
Practice Now

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

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.


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-28281{{"`Drop Array Elements From the Right`"}} javascript/data_types -.-> lab-28281{{"`Drop Array Elements From the Right`"}} javascript/arith_ops -.-> lab-28281{{"`Drop Array Elements From the Right`"}} javascript/comp_ops -.-> lab-28281{{"`Drop Array Elements From the Right`"}} end

Drop Array Elements From the Right

To remove a specified number of elements from the right of an array, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.slice() to remove the specified number of elements from the right.
  3. If you want to remove only one element, you can omit the last argument, n, and the default value of 1 will 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.

Other JavaScript Tutorials you may like