# Shuffle an array

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

Canonical: https://1loc.dev/array/shuffle-an-array/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Usage lines executed in Node.js 22 and headless Chromium; no external services
Updated: 2026-10-28

## Implementation

```javascript
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

```javascript
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.

## 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 does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/shuffle-an-array.mdx
Source file (this edition): https://github.com/akamind/1loc/blob/0a77f131b22d2ba3b7ec1728846f900c22821678/contents/shuffle-an-array.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: elkarouani
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: 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.
