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.
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.
Share Improve this question asked Dec 14, 2013 at 22:54 Dan GoodspeedDan Goodspeed 3,5905 gold badges29 silver badges35 bronze badges 4- stackoverflow./questions/2450954/… – Robert Harvey Commented Dec 14, 2013 at 22:55
- It's already somewhat randomly, as order is not guaranteed in an object. – adeneo Commented Dec 14, 2013 at 22:55
- 3 @adeneo Not guaranteed, but deterministic nevertheless. – Robert Harvey Commented Dec 14, 2013 at 22:57
- Pretty sure chrome sorts objects first by integers then lexicographically, but don't quote me – user1382306 Commented Jul 26, 2014 at 5:05
1 Answer
Reset to default 10Yes. 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 patibility 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]);})();