← Download MyJS

MyJS block

shuffle 1.0.0

Makes a shuffled copy of an array, leaving the original as it was. Every order is equally likely (a Fisher–Yates shuffle).

Download with this
Exports
shuffle
Works in
Browser and Node.js
Requires
random 1.x
Tags
random
The code of version 1.0.0
/**
 * Makes a shuffled copy of an array, leaving the original as it was. Every
 * order is equally likely (a Fisher–Yates shuffle).
 * @template T
 * @param {ArrayLike.<T>|Iterable.<T>} arr
 *    The array, or array-like or iterable object (such as a string or a Set),
 *    to shuffle.
 * @param {boolean} [useCrypto=false]
 *    If `true`, uses `crypto.getRandomValues()` instead of `Math.random()`, so
 *    the order can't be predicted.
 * @returns {Array.<T>}
 *    A new array with the same items in a random order.
 *
 * @example <caption>Shuffling a deck</caption>
 * const deck = ['A♠', 'K♠', 'Q♠', 'J♠'];
 * shuffle(deck);
 * // → a new order, like ['Q♠', 'A♠', 'J♠', 'K♠'] (deck is unchanged)
 *
 * @example <caption>Shuffling the letters of a word</caption>
 * shuffle('table').join('');
 * // → a jumble like 'ebalt'
 */
function shuffle(arr, useCrypto) {
  const copy = Array.from(arr);
  for (let i = copy.length - 1; i > 0; i--) {
    const j = random(0, i + 1, { useCrypto, returnInt: true });
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

Versions

  1. 1.0.0 Oct 23, 2026

    Initial

JSDoc