Remove specific item from array in JavaScript

We can remove element from array with different ways. But if we want to remove specific element from array then we have to think different approach.

1. Using indexOf and splice

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

let myArray = ["a", "b", "c", "d"];
console.log(myArray.splice (myArray.indexOf('c'), 1));

Above approach will work for first occurrence of element not all existing elements.

2. Using filter

This can be used to remove all occurrence of give element in the array

let myArray = ["a", "b", "c", "d"];
let toremove = 'c'
let final_array = myArray.filter((v) => v !== toremove);
console.log(final_array);

3. Using for loop and splice

This approach can also used to remove multiple occurrence of given element in the array.

let myArray = ["a", "b", "c", "d"];
let toremove = 'c'
for(let i = 0; i < myArray.length; i++){
 if(myArray[i] === toremove){
   myArray.splice(i,1)
 }
}
let final_array = myArray.filter((v) => v !== toremove);
console.log(final_array);

Leave a Reply