7

I have a for loop that looks something like

 for (var key in myObjectArray) {
   [code]
 }

I would like to do the same thing except have the order of the output shuffled every time.

Is there any easy way to do it? I can make a separate array of keys, sort them, and then do a for loop with an index… but that seems like a lot of work and rather inefficient.

Dan Goodspeed
  • 3,484
  • 4
  • 26
  • 35

1 Answers1

10

Yes. First, you need an array of keys:

var keys;
if( Object.keys) keys = Object.keys(myObjectArray);
else keys = (function(obj) {var k, ret = []; for( k in obj) if( obj.hasOwnProperty(k)) ret.push(k); return ret;})(myObjectArray);
// isn't browser compatibility fun?

Next, shuffle your array.

keys.sort(function() {return Math.random()-0.5;});
// there are better shuffling algorithms out there. This works, but it's imperfect.

Finally, iterate through your array:

function doSomething(key) {
    console.log(key+": "+myObjectArray[key]);
}
if( keys.forEach) keys.forEach(doSomething);
else (function() {for( var i=0, l=keys.length; i<l; i++) doSomething(keys[i]);})();
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Ok, thanks. That's pretty much what I was doing already and seemed pretty complicated, knowing how easy it is to sort an array. – Dan Goodspeed Dec 15 '13 at 01:50
  • Delete my "thx, me2" if you must, but I really love genius answers like this –  Jul 26 '14 at 05:04