0

function filter_list(l) {
  for (var i = 0; i < l.length; i++) {
    if (typeof(l[i]) === 'string') {
      l.splice(i, 1);
    }
  }
  return l;
}
console.log(filter_list([1, 2, 'a', 'b']));

When element 2 (index starts with 0) is spliced why doesn't the length of the array in the for loop change to 3? The last element should not be processed but it is processed.

Ele
  • 33,468
  • 7
  • 37
  • 75
  • Consider using `.filter` instead. `filter_list = arr => arr.filter(a => typeof a !== 'string')` – CertainPerformance Feb 03 '20 at 08:01
  • Please refer [Array.slice vs Array.splice](https://stackoverflow.com/questions/37601282/javascript-array-splice-vs-slice). Also note, looping on array and mutating it at the same time will cause issues. – Rajesh Feb 03 '20 at 08:01
  • If you add `console.log(l.length)` after the splice, you will see it outputs `3`. The last item was not processed. In fact, it was not removed. If it had, you would get `[1, 2]`. – Theraot Feb 03 '20 at 08:02

1 Answers1

2

Does splicing of an array reduce the value of array.length?

Yes, because splice method modifies the array inplace

The solution could be using a while loop.

function filter_list(l) {
  i = l.length;
  while (i--) {
      if (typeof(l[i]) === 'string') {
          l.splice(i, 1);
      }
  }
  return l;
}

console.log(filter_list([1, 2, 'a', 'b']));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128