Ask Your Question
1

What is the process for shuffling a JavaScript array randomly?

asked 2022-08-31 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-09-28 13:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-31 11:00:00 +0000

Seen: 9 times

Last updated: Sep 28 '21