Skip to content

shuffle

Randomly reorders elements of an array using the Fisher-Yates algorithm. Returns a new array without mutating the original. null and undefined are treated as empty arrays and return [].

Available since v2.0.0

import { shuffle } from '@helpers4/array';
shuffle<T>(array: readonly T[] | null | undefined): T[]
ParameterTypeDescription
arrayreadonly T[] | null | undefinedThe array to shuffle

T[] — A new array with the same elements in random order

Returns a new array with the same elements in random order using the Fisher-Yates algorithm.

shuffle([1, 2, 3, 4, 5])
// => [3, 1, 5, 2, 4] (random order)

The original array remains unchanged.

const original = ['a', 'b', 'c'];
const shuffled = shuffle(original);
// original is still ['a', 'b', 'c']

View source on GitHub