Loop to remove an element in array with multiple occurrences

Viewed 23923

I want to remove an element in an array with multiple occurrences with a function.

var array=["hello","hello","world",1,"world"];

function removeItem(item){
    for(i in array){
        if(array[i]==item) array.splice(i,1);
    }
}
removeItem("world");
//Return hello,hello,1
removeItem("hello");
//Return hello,world,1,world

This loop doesn't remove the element when it repeats twice in sequence, only removes one of them.

Why?

11 Answers

I thinks this code much simpler to understand and no need to pass manually each element that what we want to remove

ES6 syntax makes our life so simpler, try it out

const removeOccurences = (array)=>{
const newArray= array.filter((e, i ,ar) => !(array.filter((e, i ,ar)=> i !== ar.indexOf(e)).includes(e)))
console.log(newArray) // output [1]
}
removeOccurences(["hello","hello","world",1,"world"])

An alternate approach would be to sort the array and then playing around with the indexes of the values.

function(arr) {
    var sortedArray = arr.sort();
    //In case of numbers, you can use arr.sort(function(a,b) {return a - b;})
    for (var i = 0; sortedArray.length; i++) {
        if (sortedArray.indexOf(sortedArray[i]) === sortedArray.lastIndexOf(sortedArray[i]))
            continue;
        else
            sortedArray.splice(sortedArray.indexOf(sortedArray[i]), (sortedArray.lastIndexOf(sortedArray[i]) - sortedArray.indexOf(sortedArray[i])));
    }
}

You can use the following piece of code to remove multiple occurrences of value val in array arr.

while(arr.indexOf(val)!=-1){
  arr.splice(arr.indexOf(val), 1);
}
Related