Aller au contenu principal

shuffle()

shuffle<T>(array): T[]

Creates a shuffled copy of an array using Fisher-Yates algorithm.

remarque

Uses Fisher-Yates shuffle algorithm for unbiased randomization.


Type Parameters

T: T

The type of elements in the array.


Parameters

array: readonly T[]

The array to shuffle.


Returns: T[]

A new shuffled array.


Since

2.0.0


Note

Does not mutate the original array.


Performance

O(n) time & space.


Also known as

shuffle (Lodash, es-toolkit, Remeda, Radashi, Effect, Modern Dash, Antfu) · ❌ (Ramda)


Example

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

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

How it works?

Randomly reorders array elements using Fisher-Yates algorithm. Each permutation has equal probability.


Use Cases

Randomize quiz questions 📌

Shuffle questions to prevent memorization of order. Essential for educational apps, quizzes, or exam systems.

const questions = [
{ id: 1, text: "What is 2+2?" },
{ id: 2, text: "What is the capital of France?" },
{ id: 3, text: "Who wrote Hamlet?" },
{ id: 4, text: "What is H2O?" },
];

const randomizedQuiz = shuffle(questions);
// => Questions in random order

Randomize playlist order 📌

Create shuffled playlists for music or content. Perfect for streaming apps, video queues, or content feeds.

const playlist = ["Track 1", "Track 2", "Track 3", "Track 4", "Track 5"];

const shuffledPlaylist = shuffle(playlist);
// => ["Track 3", "Track 1", "Track 5", "Track 2", "Track 4"]

Deal cards in a game

Shuffle a deck before dealing in card games. Essential for gaming applications or simulations.

const deck = ["A♠", "K♠", "Q♠", "J♠", "10♠", /* ... */];

const shuffledDeck = shuffle(deck);
// => Randomly ordered deck

Randomize display order to avoid position bias

Shuffle product or ad listings to ensure fair exposure and prevent position bias. Important for marketplaces, ad platforms, and A/B testing where order influences clicks.

const sponsoredListings = [
{ id: "ad-1", advertiser: "Nike", bid: 2.50 },
{ id: "ad-2", advertiser: "Adidas", bid: 2.50 },
{ id: "ad-3", advertiser: "Puma", bid: 2.50 },
{ id: "ad-4", advertiser: "Reebok", bid: 2.50 },
];

// Same bid tier → randomize to give equal exposure
const fairOrder = shuffle(sponsoredListings);
// => Random order each page load, no advertiser is always first