DEV Community

Kyle Schwartz
Kyle Schwartz

Posted on

3 2

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)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more