-3

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;
xF4B
  • 86
  • 1
  • 10
  • is this all what you accomplished so far? – Observer Aug 15 '17 at 18:38
  • What have you tried? Is the result `2` because 4 and 5 are in positions 0 and 1 in both arrays of because they're present in both arrays? Essentially all you'd need are two loops inside eachother. – h2ooooooo Aug 15 '17 at 18:38
  • i tried it but it failed – xF4B Aug 15 '17 at 18:39
  • function checkArray(array, query) { var ac = 0; for (var i in array) { for (var j in query) { if (query[j] === array[i]) { ac += 1; } } } return ac; } – xF4B Aug 15 '17 at 18:39
  • @k-gun has provided a good solution here https://stackoverflow.com/a/16227294 – nagendra547 Aug 15 '17 at 18:57

5 Answers5

3

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;
  }
 }
}
2

The best way to solve your problem is by intersection.

The solution for your problem: https://stackoverflow.com/a/1885660/4120554

Marco Talento
  • 2,335
  • 2
  • 19
  • 31
2

What you're asking for is called an intersection. If you're only interested in the number of matches, this function should do the trick:

var array1 = [4, 5, 6, 7, 4, 5];
var array2 = [4, 5];

function intersectCount(arr1, arr2) {
    var c = 0;
    for(const item of arr2) {
        if (arr1.indexOf(item) != -1) c++;
    }

    return c;
}

intersectCount(array1, array2); // result: 2
1

You can use below code for your question;

var array1 = [4, 5, 6, 7, 4, 5];
var array2 = [4, 5];
function match(a1, a2) {
    var result = [];
    for(const item of a2) {
        if (a1.indexOf(item) > -1 ) {
            result.push (item);
        }
    }
    return result.length;
}
Dr. X
  • 2,890
  • 2
  • 15
  • 37
1

If you want to compare each index:

var match = (arr1,arr2)=>arr1.filter((el,i)=>el === arr2[i]).length;

If you want to count all elements that exist in both arrays, may unify one through a set:

 function match(arr1,arr2){
   var set = new Set( arr2 );
   return arr1.filter( el => set.has(el) ).length;
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151