How To Remove The Last 2 Elements From An Array In Javascript

remove the last two elements from an array in JavaScript

In this tutorial, we will show you how to remove the last two elements from an array in JavaScript. This is a common problem that many of us would face while working on JavaScript arrays. There are various solutions, and we will describe the three simple ones.  

Remove the last two elements from an array in JavaScript

Method 1: Using a for loop

We might have been familiar with using the for loop to scan through every element of our array. But now, I will show you how we can also use it to erase the last two elements.  

Let’s say we have an array called myArr that contains seven elements. And result is the new array after we have deleted the last two elements of myArr. The idea is: we will call a for loop that runs through only the first five elements of the array and add them to our result. Let’s demonstrate our idea in JavaScript:

var myArr = [34, 348, 99, 3948, 54875, 845, 37];
var result = [];

for (let i = 0; i < myArr.length - 2; i++) {
  result[i] = myArr[i];
};

console.log(result);

Output

[34, 348, 99, 3948, 54875]

Method 2: Using array.slice()

Now let’s move on to an extremely short and quick way to eliminate the last two elements of the array. JavaScript has supported us with many powerful methods to work with arrays. The array.slice() method will extract a part in our array and return it to a new one. 

Syntax:

array.slice(start, end)
  • start (optional): the starting index/point that you want to extract. 
  • end (optional): the last index/point that you want to extract.

Example: 

var myArr = [34, 348, 99, 3948, 54875, 845, 37];
var result = [];
result = myArr.slice(2, 5);
console.log(result);

Output

[ 99, 3948, 54875 ]

Now, if we want to apply this to get all of the elements except for the last two, we will do: 

result = myArr.slice(0, -2);

Completed code: 

var myArr = [34, 348, 99, 3948, 54875, 845, 37];
var result = [];
result = myArr.slice(0, -2);
console.log(result);

Output: 

[ 34, 348, 99, 3948, 54875 ]

Summary

Being able to remove the last two elements from an array in JavaScript is one of the essential skills that every JavaScript developer should know. In this tutorial, we have guided you on how to do that in 2 simple methods: using a simple for loop and array.slice().

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *