Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can shuffle a JavaScript array randomly by implementing the following algorithm:

  1. Create an empty array to hold the shuffled elements.

  2. Loop through the original array from the last index to the first.

  3. Generate a random index between 0 and the current index.

  4. Swap the element at the current index with the element at the randomly generated index.

  5. Add the swapped element to the shuffled array.

  6. Return the shuffled array.

Here is an example implementation using the above algorithm:

function shuffleArray(arr) {
  const shuffled = [];

  for (let i = arr.length - 1; i >= 0; i--) {
    const randIndex = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[randIndex]] = [arr[randIndex], arr[i]];
    shuffled.push(arr[i]);
  }

  return shuffled;
}

You can use this function to shuffle any JavaScript array randomly. Just pass your array as an argument to the function, and it will return a new array with the elements shuffled randomly.