This page looks best with JavaScript enabled

Shuffle an array in Javascript

 ·   ·  ☕ 1 min read

Write a simple logic to shuffle a given array.

Consider this array -

1
const nums = [1, 2, 3, 4, 5, 6];

You can shuffle this array by using the following code -

1
2
3
4
5
6
7
8
9
const nums = [1, 2, 3, 4, 5, 6];

nums.sort(() => Math.random() - Math.random());
console.log(nums);
/*
 [ 1, 4, 5, 2, 6, 3 ]
 [ 6, 1, 4, 2, 5, 3 ]
 ...
*/

Each run of the routine will give you a different array, thanks to Math.random() expression. Subtracting one random number from the other can give you a positive or negative result - so the sort can be totally different and random.

However, the arrays may not be unique. It is highly likely that you encounter duplicates when shifting through a larger number of possible permutations of the array.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things