Page 1 of 1

JS: Select 5 random items from array

Posted: Thu Sep 06, 2007 3:22 am
by JayBird
I have the following array

Code: Select all

images = new Array();
	
images[1] = 'image_1.jpg';
images[2] = 'image_2.jpg';
images[3] = 'image_3.jpg';
images[4] = 'image_4.jpg';
images[5] = 'image_5.jpg';
images[6] = 'image_6.jpg';
images[7] = 'image_7.jpg';
images[8] = 'image_8.jpg';
images[9] = 'image_9.jpg';
I am wanting to select 5 random unique items from that array.

It would also be helpful if the key value was kept.

Any ideas

Posted: Thu Sep 06, 2007 8:29 am
by VladSun

Code: Select all

	var r_count = 5;

	var limages = new Array();
   
	limages[0] = 'image_0.jpg';
	limages[1] = 'image_1.jpg';
	limages[2] = 'image_2.jpg';
	limages[3] = 'image_3.jpg';
	limages[4] = 'image_4.jpg';
	limages[5] = 'image_5.jpg';
	limages[6] = 'image_6.jpg';
	limages[7] = 'image_7.jpg';
	limages[8] = 'image_8.jpg';
	limages[9] = 'image_9.jpg';

	var d_count = limages.length - r_count

	var j = 0;
	while (j < d_count)
	{
		d = Math.floor(Math.random()*limages.length);
		if (limages[d])
		{
			delete(limages[d]);
			j++;
		}
	}

	var s = '';
	for( keyname in limages)
	{
		s += keyname + " : "  + limages[keyname] + "<br>";
	}

	document.write(s);
Just a notice: images array starts from 0, not from 1 ...

EDIT: Ooops, a little mistake ;)
EDIT2: When I started writing it I was hoping that delete() would remove the array element, but it appeared not to be so ...

Posted: Thu Sep 06, 2007 1:01 pm
by Weirdan

Code: Select all

var images = new Array();
   
images[1] = 'image_1.jpg';
images[2] = 'image_2.jpg';
images[3] = 'image_3.jpg';
images[4] = 'image_4.jpg';
images[5] = 'image_5.jpg';
images[6] = 'image_6.jpg';
images[7] = 'image_7.jpg';
images[8] = 'image_8.jpg';
images[9] = 'image_9.jpg';

function getRandom(min, max)
{
  return Math.random() * (max - min) + min;
}

images.sort(function(a, b) { return getRandom(0,10) > 5 ? 1 : -1; });
console.log(images);


for (var i = 0; i<5; i++) {
   console.log(images[i]);
}


Re: JS: Select 5 random items from array

Posted: Thu Sep 06, 2007 1:14 pm
by VladSun
@Weirdan
JayBird wrote: It would also be helpful if the key value was kept.

Posted: Thu Sep 06, 2007 2:17 pm
by Weirdan
Helpful != required

Posted: Fri Sep 07, 2007 3:21 am
by JayBird
Thanks guys, looks good. Cant believe it isnt simpler than that