Calling splice inside map function

user232343 picture user232343 · May 1, 2014 · Viewed 11.4k times · Source

I have following code:

var a = [{a: 1}, {a: 2}, {a: 3}];
a.map(function (item, index) {
  console.log('call');
  if (index < 1) {
    a.splice(index, 1);
  }
});

But call is printed only two times, and I expect to be printed three times. I know that splice has messed up array, but is there some workaround for this behaviour?

Thank you!

Answer

jfriend00 picture jfriend00 · May 1, 2014

If you want to modify the array while you iterate it, then often times, it's just best to use a plain old for loop because you can control the iteration and correct for your modifications.

If your modification is only a deletion of the current element, then a backwards for loop is simplest because you don't have to do any corrections when removing the current element. Here's an example:

var x = [{a: 1}, {a: 2}, {a: 3}];
for (var i = x.length - 1; i >= 0; i--) {
    if (x[i].a === 2) {
        // remove current element
        x.splice(i, 1);
    }
}

If you don't mind creating a new array as the result of the iteration, you can use other methods such as .filter().