Reputation: 21288
I want to pick random product objects from an array and place the info that they contain in four different containers. All the containers is hard coded in html and has the same class name, and I want to iterate through them.
Below you see the code, and that I'm using .each for this task, which of course doesn't work because every time the for loop runs it starts over again.
So, what is the best way to solve this?
function AddProducts(products) {
for(var i = 0; i < 4; i++) {
var number = Math.floor(Math.random() * products.length);
$('.product').each(function(index) {
$(this).find('h3').html(product[number].name);
});
}
}
<div class="row span12">
<ul class="thumbnails">
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
<li class="span3 product">
<div class="thumbnail padding">
<h3>Product name</h3>
<p>Description</p>
</div>
</li>
</ul>
</div>
Upvotes: 1
Views: 693
Reputation: 173662
If you want to pick random products and place them into each container without duplicates, you have to shuffle the array first:
function shuffle(o)
{ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
function AddProducts(products)
{
// this function modifies the array in-place
// make a copy if you need to
// products = shuffle(products.slice(0));
shuffle(products);
$('.product').each(function(i) {
if (products[i]) {
$(this).find('h3').html(products[i].name);
}
});
}
AddProducts([{name: 'foo'}, {name: 'bar'}, {name: 'baz'}, {name: 'dude'}]);
The shuffle()
function is taken from this question: How can I shuffle an array?
Also, one of your Okay, you've fixed that now :)<li>
elements has the wrong class .producer
instead of .product
.
Upvotes: 2
Reputation: 25642
Are you looking for something like this?
function AddProducts(products) {
var selectedProducts = [];
var producers = $('.producer');
for(var i = 0; i < 4; i++) {
var number = Math.floor(Math.random() * products.length);
producers.eq(i).find('h3').html(product[number].name);
}
}
Upvotes: 1
Reputation: 29932
You don't need the for loop, when already using the jQuery .each()
function.
var productTmp = product.slice(0);
$( '.product' ).each( function( index ) {
var number = Math.floor( Math.random() * productTmp.length );
$( this ).find( 'h3' ).html( productTmp[number].name );
productTmp[number] = undefined;
} );
Instead of copying the original array and deleting the used products, you could use a condition or something, to remember which products of the list already were inserted. This should prevent multiple occurrences of one product in the list (as your are picking them randomly).
Upvotes: 1