I want to iterate through the array of object and remove some of them based on some condition.
I used splice for removing the items to preserve an orderly count of items.
Then each time the item removed I would decrease the count.
But for some reason it never works:
var arr=[{img:1},{img:2},{img:3},{img:4}];
for (var i=0, count= arr.length; i < count; ) {
if ( this.arr[i].img==3 ) {
this.arr.splice(i,1);
count--;
}else i++
};
alert(JSON.stringify(arr));
…any ideas?
Looping backwards should do the trick. This avoids using counters and resetting the counter when removing an entry due to the “retreating” values.