4 Ways to Remove an Item From JavaScript Array

Can we remove a specific element from the JavaScript array? Yes, we can do it easily. There are many methods to do so. I have shared some easiest methods to delete elements from the JavaScript array.

1. Array Splicing

We can remove an item of JavaScript array easily by using the splice() method. We will find the index of the specific item first, and then splice the array to get the new array.

var array = [1, 2, 3, 4];
const item = 3; // item to remove
const index = array.indexOf(item); // find the index of the item
if (index > -1) {
    array.splice(index, 1); // if the index is valid splice the array, 2nd parameter means remove one item only
}
console.log(array);  // [1, 2, 4]

2. Array Filter

JavaScript array has some built-in methods to manipulate the array items. The array filter() is one such method used to remove the items of the array.

var array = [1, 2, 3, 4];
const item = 3; // item to remove
array = array.filter(function (value) {
    return value !== item
})
console.log(array);  // [1, 2, 4]

3. ECMAScript 6 Filter

This is the latest way to remove the items of an array using the filter() method with fewer lines of code. This method is not supported by old browsers such as Internet Explorer.

var array = [1, 2, 3, 4];
const item = 3; // item to remove
array = array.filter(value => value !== item)
console.log(array);  // [1, 2, 4]

4. ECMAScript 7 Includes Method

This method will be useful to remove multiple items from the array at once. It’s also an advanced method and so it mayn’t work in very old browsers.

let array1 = [2, 3, 5]
let array2 = [1, 2, 3, 4, 5, 3]
array2 = array2.filter(item => !array1.includes(item))
console.log(array2) // [ 1, 4 ]

Recommended Solution

The third method is one of the modern ways to delete an element from the JavaScript array. It is easier to write and execute the code.