Search code examples
javascriptarrayssplice

JavaScript does not remove all elements in one iteration, even when the condition is always satisfied


I am trying to compare two arrays with multiple objects in them, and remove elements based on a condition. I tried first in the chrome's console, and was shocked to find for some reason, the arr1 is not getting empty even when I am using an if condition that clearly is always true. After the first iteration, I always see atleast one object being left out, and after running the loop many times, it gets removed. Am I missing something? This seems such a basic JavaScript error.

var car1 = {
  type: 'das',
  model: '1',
  color: 'blue'
} //sample object
arr1 = []
for (i = 0; i < 5; i++) {
  arr1[i] = car1
} //filling object with values

for (i in arr1) {
  if (arr1[i].type == 'das') { //removing element with condition which always matches
    arr1.splice(i, 1);
  }
}
console.log(arr1);


Solution

  • You must not change array value in its loop.

    var car1 = {
      type: 'das',
      model: '1',
      color: 'blue'
    } //sample object
    arr1 = []
    for (i = 0; i < 5; i++) {
      arr1[i] = car1
    } //filling object with values
    arr2 = [];
    for (i in arr1) {
      if (arr1[i].type != 'das') { //removing element with condition which always matches
        arr2.push(arr1[i]);
      }
    }
    arr1 = arr2
    console.log(arr1);