JavaScript Delete all Occurrences in a JS Array (original) (raw)

Last Updated : 18 Nov, 2024

These are the following ways to remove all Occurrences of an element in a JS Array:

1. Using filter() method( Simple and Easy for Long Arrays)

The **filter() method creates a new array with all elements that passed the test implemented by the given callback function.

JavaScript `

function fun(a, e) { if (!a.includes(e)) { return -1; }

return a.filter(
    (item) => item !== e);

}

const a = [1, 2, 3, 4, 2, 5, 2]; const res = fun(a, 2);

console.log(res);

`

2. Using splice() method(Efficient for Mid range Array)

The **splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

JavaScript `

function fun(a, e) { if (!a.includes(e)) { return -1; }

for (let i = a.length - 1; i >= 0; i--) {
    if (a[i] === e) {
        a.splice(i, 1);
    }
}
return a;

}

const a = [1, 2, 3, 4, 2, 5, 2]; const res = fun(a, 2);

console.log(res);

`

3. Using forEach() method (Efficient for Short Array)

The **forEach() method will be used to iterate through each element of the array and make changes in it according to the condition passed inside the callback function.

JavaScript `

function fun(a, e) { if (!a.includes(e)) { return -1; }

let a1 = [];
a.forEach(item => {
    if (item !== e) {
        a1.push(item);
    }
});
return a1;

}

const a = [1, 2, 3, 4, 2, 5, 2]; const res = fun(a, 2); console.log(res);

`

4. Using reduce method(Efficient For Long Arrays)

In this approach we use the reduce method to iterate over each element of the array and accumulate the elements that do not match the element to remove.

JavaScript `

function fun(a, e) { return a.reduce((acc, c) => { if (c !== e) { acc.push(c); } return acc; }, []); }

let a = [1, 2, 3, 4, 2, 5, 2]; let e = 2; let a1 = fun(a, e); console.log(a1);

`