0

I got this code:

var counter = 0,
randoms = [],
randoms1 = [],
n;

for (n = 0; n < 5; n++) {
randoms.push(Math.floor(Math.random() * 49 + 1));
randoms1.push(Math.floor(Math.random() * 49 + 1));
}

With these 2 arrays how can I check if there is a common number in them, and this number add it to a new array?

3
  • First simple approach that comes to mind: For each element in randoms, iterate over randoms1 and compare the values. Commented Sep 24, 2014 at 15:42
  • duplicate of stackoverflow.com/questions/1885557/… Commented Sep 24, 2014 at 15:43
  • @Rhumborl im not talented in searching, not even close to searching a topic named like that lol Commented Sep 24, 2014 at 15:45

2 Answers 2

2

Loop over one of the arrays and check:

var matches = [];
for (var i = 0; i < randoms.length; i++) {
    if (randoms1.indexOf(randoms[i]) > -1) matches.push(randoms[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

--> Simple and heavy checking : Double for loop .
--> Harder but smarter and a bit lighter : use (indexOf(smthg) > -1)

--> My favorite :

randoms = [];

//Populating
for (var n = 0; n < 5; n++) {
randoms[Math.floor(Math.random() * 49 + 1)] = (Math.floor(Math.random() * 49 + 1));
}

//Checking
for (var n in randoms) {
if (randoms[randoms[n]]) console.log("Found One !");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.