Array/Since
1.38.0shuffle
Returns a new array with the elements randomly reordered without modifying the original array.
shuffle(array):T[]Parameters
arrayT[]requiredThe array whose elements should be randomly reordered.
Returns
T[]A new array containing the same elements in a randomized order.
Examples
01
Basic usage
Randomly reorder the elements of an array.
TypeScript
import { shuffle } from "@cyref/js";
const numbers = [1, 2, 3, 4, 5];
const result = shuffle(numbers);
console.log(result);
// Example: [3, 1, 5, 2, 4]02
Original array remains unchanged
The function creates a copy before shuffling, so the original array is not modified.
TypeScript
import { shuffle } from "@cyref/js";
const numbers = [1, 2, 3, 4, 5];
const result = shuffle(numbers);
console.log(numbers);
// [1, 2, 3, 4, 5]
console.log(result);
// Randomized order03
With strings
The function can randomly reorder arrays containing strings.
TypeScript
import { shuffle } from "@cyref/js";
const languages = [
"JavaScript",
"TypeScript",
"Python",
"Go",
];
const result = shuffle(languages);
console.log(result);
// Example: ["Go", "JavaScript", "Python", "TypeScript"]04
Empty array
An empty array returns a new empty array.
TypeScript
import { shuffle } from "@cyref/js";
const result = shuffle([]);
console.log(result);
// []Built with@cyref/js·Official documentation