Randomize an Array in JavaScript

Last Updated On Wednesday 13th Apr 2022

shuffle array javascript

javascript array shuffle

Shuffle an Array Using Fisher-Yates Shuffle Algorithm

js shuffle array

• The Fisher-Yates shuffle is a highly efficient and completely unbiased way to randomize the elements in an array.
• It’s a fairly simple method.
• Start at the end of the list, and swap the last element with a random element from earlier in the list.
• Go down one and repeat, until you’re at the beginning of the list, with all of the shuffled elements at the end of the list.
	function shuffle(arr) {
const len = arr.length;
const shuffled = new Array(len);

let i = 0;
let ran;
const end = len - 1;

while (i <= end) {
ran = ~~(Math.random() * (i + 1));

if (ran !== i) {
shuffled[i] = shuffled[ran];
}

shuffled[ran] = arr[i];

i++;
}

return shuffled;
}

console.log(shuffle([1, 2, 3, 4]));



javascript randomize array

You can do it easily with map and sort.
Put Each element in the array in an object, and give it a random sort key and sort using that key, then map back to the original objects.

	let arr = ['a','b','q', 1, 2, 3 ];

let newArr = arr
.map((value) => ({ value, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ value }) => value);

console.log(newArr);



javascript randomize array

ES6 Pure using array.reduce

	function getShuffledArr (arr){
return arr.reduce(
(newArr, _, i) => {
var rand = i + ( Math.floor( Math.random() * (newArr.length - i) ) );
[newArr[rand], newArr[i]] = [newArr[i], newArr[rand]]
return newArr
}, [...arr]
)
}



Random Array in Javascript

	function randomizeArray(arr) {
var curArr = [],
start;

for (var i = arr.length; i >= arr.length && i > 0; i--) {
start = Math.floor(Math.random() * arr.length);
curArr.push(arr.splice(start, 1)[0]);
}

return curArr;
}


	randomizeArray([2, 4, 5, 6, 8, 9]);

// [8, 2, 4, 5, 6, 9]

randomizeArray([28, 25, 77, 66, 88, 99]);

// [ 77 , 99, 66, 28, 88, 25 ]