Open In App

JavaScript Program to Remove All Occurrences of an Element in an Array

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given an array and a particular number. We need to check for the existence of the element in the array. If the element is not present in the array we will return -1. Otherwise, we will remove all the occurrences of the given element from the array.

Using filter() method

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

Example: The below code removes all occurrences of an element from an Array using the filter() method in JavaScript.

Javascript




function removeElement(arr, elem) {
    if(!arr.includes(elem)){
        return -1;
    }
     
    return arr.filter(
        (item) => item !== elem);
}
 
const array =
    [1, 2, 3, 4, 2, 5, 2];
const result1 =
    removeElement(array, 2);
const result2 =
    removeElement(array, 6);
console.log(result1);
console.log(result2);


Output

[ 1, 3, 4, 5 ]
-1

Using splice() method

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

Example: The below code removes all occurrences of an element from an Array using the splice() method in JavaScript.

Javascript




function removeElement(arr, elem) {
    if (!arr.includes(elem)) {
        return -1;
    }
 
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i] === elem) {
            arr.splice(i, 1);
        }
    }
    return arr;
}
 
const array =
    [1, 2, 3, 4, 2, 5, 2];
const result1 =
    removeElement(array, 2);
const result2 =
    removeElement(array, 6);
console.log(result1);
console.log(result2);


Output

[ 1, 3, 4, 5 ]
-1

Using forEach() method

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

Example: The below code removes all occurrences of an element from an Array using the forEach() method in JavaScript.

Javascript




function removeElement(arr, elem) {
    if (!arr.includes(elem)) {
        return -1;
    }
     
    let newArray = [];
    arr.forEach(item => {
        if (item !== elem) {
            newArray.push(item);
        }
    });
    return newArray;
}
 
const array =
    [1, 2, 3, 4, 2, 5, 2];
const result1 =
    removeElement(array, 2);
const result2 =
    removeElement(array, 6);
console.log(result1);
console.log(result2);


Output

[ 1, 3, 4, 5 ]
-1


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads