Ask Your Question
3

What is the method for using an if-loop to shuffle values from other arrays and create a new array?

asked 2021-08-02 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-11-24 17:00:00 +0000

lalupa gravatar image

Here's one method for using an if-loop to shuffle values from other arrays and create a new array:

  1. Initialize an empty array to hold the shuffled values:
let shuffledArray = [];
  1. Determine how many values you want to shuffle (this can be the length of an existing array or a specific number):
let numValuesToShuffle = 10;
  1. Create a loop to iterate through the desired number of values:
for (let i = 0; i < numValuesToShuffle; i++) {
  // code to shuffle values will go here
}
  1. Inside the loop, use an if-statement to randomly select a value from one of your source arrays and add it to the shuffledArray:
let randNum = Math.floor(Math.random() * 2); // generates a random number between 0 and 1
if (randNum === 0) {
  let randomIndex = Math.floor(Math.random() * array1.length);
  shuffledArray.push(array1[randomIndex]);
} else {
  let randomIndex = Math.floor(Math.random() * array2.length);
  shuffledArray.push(array2[randomIndex]);
}
  1. Repeat this process for as many values as you want to shuffle.

Note: This method assumes that you have existing arrays from which you want to shuffle values. If you need to create new arrays with randomized values, you would need to modify this code accordingly. You could also modify the if-statement to shuffle values from more than two arrays.

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: 2021-08-02 11:00:00 +0000

Seen: 7 times

Last updated: Nov 24 '21