2

This code is going to remove all the 'b' elements out of the array. It does, but not entirely. There is still one 'b' left after the code is executed. Why is it happening? When we set the 3rd argument into splice method to change a 'b' element into another, it works well. But with only two arguments, does not. Why?

let array = ['a','b','c','b','d','e','d','b','b','b','d','d'];

var i = 0;

while (i < array.length){

if (array[i] === 'b'){
    array.splice(i,1);
}
i++;
}
console.log(array);
  • You're incrementing `i` on each iteration, but when you remove a "b" you'll skip an extra character because removing that one makes the array shorter. – Pointy May 09 '18 at 10:15

1 Answers1

6

When the splice method is applied, the array is re-indexed. You will skip over an index when one element is removed from your given array.

The solution is to decrement the value of i after splice.

let array = ['a','b','c','b','d','e','d','b','b','b','d','d'];
var i = 0;
while (i < array.length){
  if (array[i] === 'b'){
      array.splice(i,1);
      i--;
  }
  i++;
}
console.log(array);

In this situation, I suggest you to use filter method.

let array = ['a','b','c','b','d','e','d','b','b','b','d','d'];
array = array.filter(elem => elem != 'b');
console.log(array);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • In subsequent step I want to filter out every other occurance of element 'b' in that array.Not all of them. I couldn't achive it using filter(). Will I get job done using this method? – Krzysiek Kowalski May 09 '18 at 11:03