shuffle array in javascript

To shuffle an array in JavaScript, one way is to use the Fisher-Yates (aka Knuth) shuffle algorithm. Here's the code:

index.tsx
function shuffleArray(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}
186 chars
8 lines

This function takes an array as an argument and shuffles it in place using the algorithm. The array is returned as the result so you can easily use it in your code.

related categories

gistlibby LogSnag