How to remove an element from the array in JavaScript

January 04, 2020 No comments JavaScript QA Snippets Examples Vanilla JS

1. Introduction

In this short article, we are going to present methods to remove a specified element from an array in JavaScript.

2. Using splice() function

To remove an element from the array we can use splice() function that changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To remove an element at index i we can use array.splice(i, 1);

const arr = ["2","3","4","5"];
console.log('Before splice', arr);

arr.splice(2, 1);
console.log('After splice', arr); // ["2","3","5"]

3. Using delete

In case you want to remove an element from the array but also keep indexes of other elements unchanged, you can use delete method.

const arr = ["2","3","4","5"];
console.log('Before delete', arr);
delete arr[2];

console.log('After delete', arr); // ["2","3",undefined,"5"]

4. Using ES6 filter method

If we want to remove an element from array using immutable approach (original array stay unchanged) we can use filter method.
const arr = [2,3,4,5,6,7,8];
const even = arr.filter(el => el % 2 === 0);

console.log('After filter', even); // [2,4,6,8]

5. Conclusion

In this article, we presented a method to remove a particular element from an array in JavaScript. Fortunately, JavaScript comes with dedicated method splice() to modify contents of an array in place, although the better way is to keep original array unchanged (immutable) and just use filter to get only elements that we want to process in the next step.
{{ message }}

{{ 'Comments are closed.' | trans }}