xF4B xF4B -3 years ago 91
Javascript Question

Find Matches in Array

I have

array1 = [4, 5, 6, 7, 4, 5];
and
array2 = [4, 5]
.

And I want to match array2 in array1 and to output the number of times it matched.

var array1 = [4, 5, 6, 7, 4, 5];
var array2 = [4, 5];
function match(a1, a2) {
//matches 4,5 twice bc it is in array1
}

match(array1, array2) //output: 2;

Answer Source

You have to use a nested loop and compare each index of both arrays with each other.

var count = 0;
for (var i = 0; i < a1.length; i++)
{
 for (var j = 0; j < a2.length; j++)
 {
  if (a1[i]==a2[j])
  {
   count +=1;
  }
 }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download