Remove Last n Elements From An Array In JavaScript

To remove last n elements from an array in JavaScript, you can use any of the following methods –

  1. Use the Array.splice() method
  2. Use the Array.slice() method

Let’s discuss each of these methods in detail below.

remove last n elements from an array in javascript

Use The Array.slice() Method

If you want to remove last n elements from an array in JavaScript, you can use the Array.slice() method. This method is used to extract a part of an array and return it as a new array.

The syntax of the Array.slice() method is –

array.slice(start, end)

Where –

start – The starting index of the part of the array you want to extract.

end – The ending index of the part of the array you want to extract.

For example, if we have an array –

var arr = [“a”, “b”, “c”, “d”];

And we want to remove the last two elements from it, we can do so using –

var arr = [“a”, “b”, “c”, “d”];

var newArr = arr.slice(0, -2);

console.log(newArr); // [“a”, “b”];

This will give us the following output –

[“a”, “b”];

In the above code, we have first declared an array –

var arr = [“a”, “b”, “c”, “d”];

Then, we have used the Array.slice() method to remove the last two elements from it and store it in a new array.

Finally, we have logged the new array to the console –

console.log(newArr); // [“a”, “b”];

Note that this method doesn’t change the original array, and instead returns a new array with the last 2 elements removed.

Use The Array.splice() Method

If you want to remove last n elements from an array in JavaScript, you can also use the Array.splice() method. This method is used to change the contents of an array by removing or adding elements to it.

The syntax of the Array.splice() method is –

array.splice(start, deleteCount, items)

Where –

start – The index at which to start changing the array.

deleteCount – The number of elements to remove.

items – The elements to add to the array.

For example, if we have an array –

var arr = [“a”, “b”, “c”, “d”];

And we want to remove the last two elements from it, we can do so using –

var arr = [“a”, “b”, “c”, “d”];

arr.splice(-2);

console.log(arr); // [“a”, “b”];

This will give us the following output –

[“a”, “b”];

In the above code, we have first declared an array –

var arr = [“a”, “b”, “c”, “d”];

Then, we have used the Array.splice() method to remove the last two elements from it.

Finally, we have logged the new array to the console –

console.log(arr); // [“a”, “b”];

Note that this method changes the original array.

Conclusion

In this article, we looked at how to remove last n elements from an array in JavaScript. We discussed two methods that can be used for this – the Array.slice() method and the Array.splice() method. We also looked at an example of each of these methods in action.

Leave a Comment