Reputation: 5619
I am trying to figure out how to build a forEach loop with an unknown number of elements. Randomly pick one, do XYZ to it. Make it visible. Remove that element from consideration. Repeat picking a random number from remaining elements.
My thoughts so far are to make an array of the elements id's. Use the array.forEach() to loop over them. Select an element at random from the array. Execute XYZ then remove selected id from array then repeat till forEach expires.
So first of all if you can think of a better way I'm open to any and all ideas.
I didn't get far before I hit my first roadblock and that is dynamically generating the array of id's.
I get the number of elements (they will always be children of the parent so no worries there.
//get count of all elements and loop till all are visible
var elementCount = $('#PartialsContainer').children().size();
Next I goto generate my array but it results in one element in the array holding the value of elementCount.
//create array of quantity
var elementArray = $.makeArray( elementCount );
So I could do a loop through elements getting their id like this but surely there is a better way?
for (var i = 0; i < elementCount; i++)
{
elementArray.push( $element[i] //its pseudo code I know it won't work );
}
Thank you for any ideas / tips on improving this design / approach.
Upvotes: 1
Views: 798
Reputation: 388316
Try something like
var $els = $('#PartialsContainer').children();
while($els.length){
var $el = $els.eq(Math.floor(Math.random() * $els.length));
//do something with $el
$els = $els.not($el);
}
Demo: Fiddle
Upvotes: 2