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?

Alpha2k
  • 2,212
  • 7
  • 38
  • 65
  • First simple approach that comes to mind: For each element in `randoms`, iterate over `randoms1` and compare the values. – Felix Kling Sep 24 '14 at 15:42
  • duplicate of http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript/1885569#1885569 – Rhumborl Sep 24 '14 at 15:43
  • @Rhumborl im not talented in searching, not even close to searching a topic named like that lol – Alpha2k Sep 24 '14 at 15:45

2 Answers2

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]);
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
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 !");
}
Hotted24
  • 502
  • 3
  • 8