Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

randomly match a value of one array to a value of another array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I honestly have no idea what to try.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading