Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  11] [ 3]  / answers: 1 / hits: 18172  / 10 Years ago, wed, april 30, 2014, 12:00:00

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!


More From » splice

 Answers
187

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;
});

[#71226] Tuesday, April 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahk

Total Points: 166
Total Questions: 94
Total Answers: 117

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;