DEV Community

Kyle Schwartz
Kyle Schwartz

Posted on

Shuffle JavaScript Array in 1 Line

const shuffle = () =>
    arr
        .map((e) => [e, Math.random()])
        .sort((a, b) => a[1] - b[1])
        .map((e) => e[0]);
Enter fullscreen mode Exit fullscreen mode

Although slightly longer than other implementations, it maintains an even distribution.

let results = {};

for (let i = 0; i < 100000; i++) {
    const a = shuffle();
    results[a] = results[a] ? results[a] + 1 : 1;
}

console.log(results);

// { '3,2,1': 16647,
//   '1,3,2': 16877,
//   '2,1,3': 16781,
//   '1,2,3': 16510,
//   '3,1,2': 16856,
//   '2,3,1': 16329 }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)