How can I remove all occurrences of a specific element from an array in JavaScript?
Benjamin C
benjamin c profile pic

To remove all occurrences of a specific element from an array in JavaScript, you can use various techniques. Here's a step-by-step guide on how to achieve this: 1. Define the array from which you want to remove the element:

1
2
3

   let array = [1, 2, 3, 4, 3, 5, 3];
   

Replace[1, 2, 3, 4, 3, 5, 3] with your array. 2. Using thefilter() method:

1
2
3
4

   const elementToRemove = 3; // Replace with the element you want to remove
   array = array.filter((element) => element !== elementToRemove);
   

Thefilter() method creates a new array containing all the elements that do not match the specified element to remove. It uses a callback function that compares each element with the element to be removed, filtering out the matching elements. 3. Using a loop:

1
2
3
4
5
6
7
8

   const elementToRemove = 3; // Replace with the element you want to remove
   for (let i = array.length - 1; i >= 0; i--) {
     if (array[i] === elementToRemove) {
       array.splice(i, 1);
     }
   }
   

This code iterates over the array in reverse order and removes the element at the current index using thesplice() method whenever it matches the element to remove. The loop runs until it reaches the first element of the array. 4. Using thereduce() method:

1
2
3
4
5
6
7
8
9

   const elementToRemove = 3; // Replace with the element you want to remove
   array = array.reduce((accumulator, element) => {
     if (element !== elementToRemove) {
       accumulator.push(element);
     }
     return accumulator;
   }, []);
   

Thereduce() method accumulates elements in a new array while excluding the ones that match the element to remove. The callback function adds the element to the accumulator array only if it doesn't match the element to be removed. Choose the method that best suits your needs and adjust the code as necessary to fit your specific use case. All these approaches are commonly used to remove all occurrences of a specific element from an array in JavaScript. Note that these methods create a new array or modify the original array, depending on the approach. If you need to keep the original array intact, make a copy of it before performing the removal.