Remove Array Elements From the End

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to remove elements from the end of an array in JavaScript. We will use the Array.prototype.slice() method to create a new array with n elements taken from the end of the original array. 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-28642{{"`Remove Array Elements From the End`"}} javascript/data_types -.-> lab-28642{{"`Remove Array Elements From the End`"}} javascript/arith_ops -.-> lab-28642{{"`Remove Array Elements From the End`"}} javascript/comp_ops -.-> lab-28642{{"`Remove Array Elements From the End`"}} end

How to Remove Array Elements From the End in JavaScript

To remove elements from the end of an array in JavaScript, you can use the Array.prototype.slice() method. Here's how you can do it:

const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);

This function creates a new array with the last n elements of the original array. Here's how you can use it:

takeRight([1, 2, 3], 2); // [ 2, 3 ]
takeRight([1, 2, 3]); // [3]

To use this function, open the Terminal/SSH and type node to start practicing coding.

Summary

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

Other JavaScript Tutorials you may like