shuffle an array in typescript

To shuffle an array in TypeScript, you can use a Fisher-Yates shuffle algorithm. Here is an example:

index.ts
function shuffleArray<T>(array: T[]): T[] {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
213 chars
8 lines

This function takes an array as input and returns a new array with its elements shuffled randomly.

The algorithm works by iterating backwards starting from the last element of the array. For each element, it randomly selects another element before it and swaps their positions using array destructuring syntax.

Note that this function modifies the original array in place. If you want to keep the original array unchanged, you can make a copy of it before calling the function.

gistlibby LogSnag