Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript remove all occurrences of a value from an array

I am using the snippet below to remove all occurrences of a value (i.e. 97 in this case) from an Array. I am unable to understand why the output array has a value 97 in it. When I remove 32 it removes all 32s from the array. Same with 6. What's wrong with 97 here? Kind of strange for me. (I was thinking may be 97 is not typed properly or something).

var inputArr = [3, 97, 32, 6, 97, 2, 9,32, 1, 32, 97, 97, 6, -1, 5];

function removeItem(array, item) {
  for(i = 0; i<array.length; i++){
    if(array[i] == item) {
      array.splice(array.indexOf(item), 1);
    }
  }
}
removeItem(inputArr, 97); removeItem(inputArr, 32); removeItem(inputArr, 6);

document.getElementById("output").innerHTML = inputArr;
<p id="output"></p>
like image 959
Kiran Dash Avatar asked Feb 04 '18 12:02

Kiran Dash


2 Answers

While you mutating the array and you increment the index on splicing as well, you could take another approach and start from the end of the array. That means the following items are still available at their original index and could be checked and spliced if necessary, without leaving some unspliced values.

function removeItem(array, item) {
    var i = array.length;

    while (i--) {
        if (array[i] === item) {
            array.splice(array.indexOf(item), 1);
        }
    }
}

var inputArr = [3, 97, 32, 6, 97, 2, 9, 32, 1, 32, 97, 97, 6, -1, 5];

removeItem(inputArr, 97);
removeItem(inputArr, 32);
removeItem(inputArr, 6);

console.log(inputArr);
like image 65
Nina Scholz Avatar answered Oct 27 '22 00:10

Nina Scholz


Issue is related to the sibling 97s - 1, 32, 97, 97, 6. When you splice the first 97 in this order, the next 97 changes it's index and goes into the first one. but variable i is tracking after that item.

When you remove an item, decrease the index via --i.

Also you can do it via filter function. This will create a new array and you just need to return it. Here I have created and object with input array and a function which filters the input and returns the current object. This will let you to cascade the functions which I think is beautiful from the code style and can help you in something.

const obj = {
   input: [3, 97, 32, 6, 97, 2, 9,32, 1, 32, 97, 97, 6, -1, 5],
   removeItem(item) {
      this.input = this.input.filter(i => i !== item);
      return this;
   }
}

const output = obj.removeItem(97)
                  .removeItem(32)
                  .removeItem(6); 
      
console.log(output.input);
like image 39
Suren Srapyan Avatar answered Oct 27 '22 00:10

Suren Srapyan