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!
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!
Share Improve this question edited Apr 30, 2014 at 22:49 Brad 163k55 gold badges377 silver badges552 bronze badges asked Apr 30, 2014 at 22:47 user232343user232343 2,1185 gold badges22 silver badges35 bronze badges3 Answers
Reset to default 6the 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.
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()
.
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;
});