Home > Net >  randomly match a value of one array to a value of another array
randomly match a value of one array to a value of another array

Time:11-12

I have 2 arrays with the same values and I want to match randomly one value of array A to one value of array B and make sure the value is not the same.

var arrayA = ["john","max","james","nicolas"];
var arrayB = ["john","max","james","nicolas"];

I am trying to have:

  • john max
  • max nicolas
  • james john
  • nicolas james

What I don't want:

  • john max
  • nicolas nicolas (here is the issue)
  • james john
  • max james

I honestly have no idea what to try.

CodePudding user response:

Because both arrays contain the same values, there's no need for different arrays - a single one is enough.

After getting the first random value, continually generate another, repeating while the value matches. Once the value doesn't match, break out.

const array = ["john","max","james","nicolas"];

const val1 = array[Math.floor(Math.random() * array.length)];
let val2;
do {
  val2 = array[Math.floor(Math.random() * array.length)];
} while (val1 === val2);
console.log(val1, val2);

Or, after picking the first, filter the array by values that match what was picked before making the second choice.

const array = ["john","max","james","nicolas"];

const val1 = array[Math.floor(Math.random() * array.length)];
const filteredArray = array.filter(val => val !== val1);
const val2 = filteredArray[Math.floor(Math.random() * filteredArray.length)];
console.log(val1, val2);

  • Related