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