A shuffled array is an array in which the elements have been randomly reordered. It means that the elements are no longer in their original order, but are arranged in a random sequence. Shuffling is useful in various contexts, such as games (e.g., shuffling a deck of cards), randomizing questions in a quiz, or any scenario where a random ordering of elements is needed.
Syntax
array.sort(() => Math.random() - 0.5);
Example
[1,2,3,4,5].sort(() => Math.random() - 0.5);
The expression array.sort(() => Math.random() - 0.5);
shuffle the elements of an array in a random order. Math.random()
generates a random number between -0.5
and 0.5
. The random value determines the shuffle order: negative for placing the first element before the second, zero for no preference, and positive for placing the second element before the first.
Conclusion
This method provides a quick way to shuffle an array, but it’s not perfectly uniform for large arrays due to the nature of floating-point precision and the randomness of Math.random()
. For such cases, consider using a more efficient shuffling algorithm like the Fisher-Yates shuffle.