Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an array with "holes" in JavaScript

I have got an array from which some items are going to be removed; but some loops are still running on them, so I want to simply skip the places where I remove my objects

I know that the syntax for(i in array) should do this because it iterates on the index, but how should I remove my items then ? Because when i do array[4] = null, my for just doesn't care and goes on trying to use the value at 4.

I also tried to check if !null but without success... thank you

like image 666
Rayjax Avatar asked Oct 24 '25 00:10

Rayjax


1 Answers

If you want to remove an item without leaving a hole, you should use .splice()

myarray.splice(idx, 1);

But if you're saying that you want the holes there, but want to skip them, then you can use delete to remove the item (leaving a hole), and use .forEach() for the iteration, which skips holes.

delete myarray[idx];

// ...

myarray.forEach(function(item, i) {
    // holes will be skipped
});

To support older browsers like IE8 and lower, you'll need to add a compatibility patch for forEach().

  • MDN .forEach() (Ignore the shorter patch. It's a poor non-compliant version.)
like image 197
I Hate Lazy Avatar answered Oct 25 '25 14:10

I Hate Lazy