This function shuffles the elements of an array.
JavaScript:
let shuffle = arr => arr.sort(() => Math.random() - 0.5);
// Example
console.log(shuffle([1, 2, 3, 4, 5])); // random order, such as [4, 1, 5, 2, 3]
console.log(shuffle(['a', 'b', 'c', 'd', 'e'])); // random order, such as ['e', 'a', 'b', 'c', 'd']
TypeScript:
let shuffle = (arr: T[]): T[] => arr.sort(() => Math.random() - 0.5);
// Example
console.log(shuffle([1, 2, 3, 4, 5])); // random order, such as [4, 1, 5, 2, 3]
console.log(shuffle(['a', 'b', 'c', 'd', 'e'])); // random order, such as ['e', 'a', 'b', 'c', 'd']