Alex Rivera | Logout

Javascript iterating through sparse array

Asked 2012-05-13T03:27:05.170
15

I have a sparse array (indexes are not consecutive) like this:

var testArray = { 0: "value1", 5: "value2", 10: "value3", 15: "value4" };

I would simply like to iterate through each item, do some stuff, and be able to break under a certain condition.

I am fairly new to Javascript and I didn't find a proper way to do it. Here is what I tried:

  1. Built-in "for..in". It seems that this is not the correct way to iterate through an array

  2. forEach from ECMASCRIPT5. This one iterate correctly, but I cannot break from the loop.

  3. _.each() from Underscore.js. Same result as #2.

  4. $.each() from JQuery. With this one I can break by returning false, but it won't iterate correctly. For the above example, instead of iterating at 0, 5, 10, 15, it will iterate at 0,1,2,3,4,5,6... which is obviously not what I expect.

So my question is: Is there an easy way to iterate a sparse array with the possibility to break during the loop in Javascript or would it be better to use another data structure like an hashtable? If so, any recommandation?

Thanks!

Edit
Report

2 Answers

3

For..in isn't the worst thing when you're working on an object hash. It's to be avoided for use with arrays ([]), but it should be ok here:

var val;
for (index in testArray) {
  if (index == 10) {
    break;
  } else {
    val = testArray[index];
  }
}
answered 2012-05-13T03:33:01.143
2

First thing you have to kiss-bye-bye is "Array". There is no real Array in ECMAscript (forgetting about typed-arrays and binary trickery).

So what you've got there is a plain Object. To iterate over that, I'd suggest to use .forEach if you're cool with ES5. If you need to early break that iteration, you might want to use ES5 methods like .some() or .every(), like:

Object.keys( testArray ).some(function( key ) {
    if( +key < 15 ) {            
        return true;
    }

    console.log(key, testArray[key]);
});

This would interrup the iteration when a key is encountered which numerical value is not lower than 15, by returning true.

answered 2012-05-13T03:36:08.443

Your Answer