Shuffle Array Element di JavaScript


Salah seorang temanku bertanya, apa algoritma yang dipergunakan untuk melakukan shuffle (mengurutkan secara random) element di array JavaScript?

function shuffle(array) {
	var tmp, current, top = array.length;
	
	if (top) {
		while (--top) {
			current = Math.floor(Math.random() * (top + 1));
			tmp = array[current];
			array[current] = array[top];
			array[top] = tmp;
		}
	}
	
	return array;
}

referensi : Is it correct to use JavaScript Array.sort() method for shuffling?

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: