Muhaimin
Muhaimin

Reputation: 1643

How to iterate over an array of object then remove each element in JavaScript

someArray = [{name:"Ibrahim", cid:322}, {name:"Ismail", cid:423}];

As you can see above, this is simple task to do but I haven't found solid way to iterate over this array, perform some action, and later result as below

someArray = [];

So far this is what i have come trough

for (var i = 0; i < someArray.length; i++) {
    someArray[i].action()
    someArray.splice(0,1);
}

it just don't work as I expected. Appreciate somebody can provide me the way. Thanks

Upvotes: 0

Views: 52

Answers (6)

Riten Vagadiya
Riten Vagadiya

Reputation: 123

You need to decide the length first, and not count it on each iteration (it is also good for performance)

Here is a fiddle: http://jsfiddle.net/hW4Mm/22/

The magic is in this line: var len = someArray.length;

That should work.

Upvotes: 0

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

wutt??

you want to modify the collection while iterating? you need to put additional logic after removing the item

you have 2 items, ibrahim and ismail

when entering the first loop (i = 0, length = 2, 0 < 2 => iterate)
 ibrahim action is called
 and then the ibrahim is removed
when entering the second loop (i = 1, length = 1, 1 < 1 => quit loop)

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074138

The reason it doesn't work is that you're incrementing i, but modifying the array.

The simple way is just clear out the array at the end:

for (var i = 0; i < someArray.length; i++) {
    someArray[i].action();
}
someArray.splice(0,someArray.length);

but if you have to update the array on each pass

while (someArray.length) {
    someArray[0].action();
    someArray.splice(0,1);
}

or if it's okay to replace the array rather than emptying it:

for (var i = 0; i < someArray.length; i++) {
    someArray[i].action()
}
someArray = [];

Note that in that last case, if any other variable or property is pointing to the old array, it won't get cleaned out. But if someArray is the only reference to it, then you could just assign a blank array to it.

Upvotes: 3

iLikePrograms
iLikePrograms

Reputation: 468

This can be done really simply, by looping over the array, then making it a blank array. Hope this was helpful!

someArray.forEach(function (person) { // Use Array#forEach to itterate
    person.action(); // Call action on person (person = someArray[i] in your example)
});

someArray = []; // Now make someArray = to a blank array

Upvotes: 0

hsz
hsz

Reputation: 152206

Just try with:

while (someArray.length) {
    someArray[0].action();
    someArray.splice(0,1);
}

Or:

while (someArray.length) {
    someArray.shift().action();
}

Upvotes: 0

Johan
Johan

Reputation: 35194

Why not simply do

for (var i = 0; i < someArray.length; i++) {
    someArray[i].action();
}

someArray = [];

Upvotes: 0

Related Questions