Shuffle an array

Return a new array in random order, every order equally likely.

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

shuffle-an-array.js
function shuffle(values) {
  const result = [...values];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}

Usage

usage.js
const deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
shuffle(deck).toSorted((a, b) => a - b); // → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
deck; // → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(deck); // e.g. [9, 1, 10, 6, 8, 5, 2, 3, 7, 4]

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

Know the limits

  • Fisher–Yates in O(n). The original sorted by random keys, which is also unbiased but O(n log n); avoid sort(() => Math.random() - 0.5), which is biased.
  • Math.random is not cryptographic. For draws people could dispute, use crypto.getRandomValues, as in Generate a random string from given characters.
  • The input array is unchanged.

The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Shuffle an array from the original 1loc collection by Nguyen Huu Phuoc, with elkarouani. Copyright (c) 2020 phuoc-ng. MIT licensed.

Fisher–Yates in O(n) instead of sorting by random keys. Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.

Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/shuffle-an-array.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.