1

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.

3
  • Can you not iterate over the jQuery object? Commented Dec 12, 2013 at 0:28
  • 2
    size() is deprecated... use length property instead Commented Dec 12, 2013 at 0:31
  • 1
    $('#PartialsContainer').children().each(function() { ...} ); Commented Dec 12, 2013 at 0:32

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

The .eq() was new to me and reading up on it shows it is exactly what I was looking for. Then Math.random() generates a random number between 0 to 1 then multiply it and take the floor finally pop it off the stack. Thank You very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.