shuffle()
shuffle<
T>(array):T[]
Creates a shuffled copy of an array using Fisher-Yates algorithm.
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