Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling splice inside map function

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!

like image 655
user232343 Avatar asked Oct 27 '25 06:10

user232343


2 Answers

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.

like image 103
richmb Avatar answered Oct 28 '25 18:10

richmb


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

like image 21
jfriend00 Avatar answered Oct 28 '25 18:10

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!