Anonymous
Anonymous

Reputation: 4632

How to remove some items by iterating over the array of objects?

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?

Upvotes: 2

Views: 2382

Answers (5)

Givius
Givius

Reputation: 1008

try this loop, I haven't tested but should work.

var arr=[{img:1},{img:2},{img:3},{img:4}];
for (var i=arr.length-1; i >= 0; i--) {
    if ( arr[i].img==3 ) {
        arr.splice(i,1);
    }
};
alert(JSON.stringify(arr));

Upvotes: 0

RobG
RobG

Reputation: 147403

Simpler to loop through the array backwards, then you don't have to adjust the iterator:

var i = arr.length;
while ( i-- ) {

  if ( arr[i].img == 3 ) {
    arr.splice(i,1);
  }
}

Upvotes: 1

azhrei
azhrei

Reputation: 2323

You're referring to this.arr instead of just arr.

Delete the two this. from the code, and it works. :-)

Upvotes: 0

Joseph
Joseph

Reputation: 119847

Looping backwards should do the trick. This avoids using counters and resetting the counter when removing an entry due to the "retreating" values.

var i;
for (i = arr.length; i--;) {
    if (arr[i].img === 3) {
        arr.splice(i, 1);
    }
};

Upvotes: 2

mjgpy3
mjgpy3

Reputation: 8947

I have dealt with this same difficulty before. My solution was to loop through the array and compose another array of elements to remove. loop through the list of elements to remove in reverse and remove them. This worked well for me.

Michael G.

Upvotes: 0

Related Questions