Question

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!

Was it helpful?

Solution 2

Make a shallow copy of the array:

a.slice().map(function (item, index) {

By the way, you should maybe use forEach since you're not returning any value.

Or even better, have you considered using filter instead?

var a = [{a: 1}, {a: 2}, {a: 3}].filter(function (item, index) {
  console.log('call');
  return index >= 1;
});

OTHER TIPS

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().

the callback in map has a third argument which is the array it self

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

This if from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top