JavaScript – Shuffle an array in a random order

To shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s explore both approaches here.

Method 1: Using sort() and Math.random():

let arr = [1, 2, 3, 4, 5];
arr.sort(() => Math.random() - 0.5);
console.log(arr);

The above sort() method sorts the array using a custom compare function. The compare function returns a random value between -0.5 and 0.5. This random value makes the sort() function randomly reorder the elements of the array. In this way, the array is shuffled into a random order each time it’s run.

Method 2: Using map() & sort():

let arr = [1, 2, 3, 4, 5];

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

console.log(shuffled);

Firstly, map() converts each element of the array into an object with two properties: value (the original element) and sort (a random number generated by Math.random()). hen Sorts these objects by their sort property, which randomly reorders the array based on the generated random values.

Similar Reads