user6758349
user6758349

Reputation:

How to compare 2 arrays and get count of each matching item

Say an AJAX call returns 2 arrays on success. The arrays returned are different everytime, but there could be some elements in common. For example,

array1 = [a, b, c, d]
array2 = [a, b, b, b, a, c, b, c, c]

Now I want to get the number of times each element of array 1 appeared in array 2, in this case, the results would be:

a: 2
b: 4
c: 3
d: 0

I have the following code that compares the two arrays, but I can't figure out how to keep a counter, do I have to construct a new 2d array for each element of array1? In which case, how do I construct the array without knowing the elements inside of it first?

success: function (array1, array2) {
  for (var i = 0; i < array1.length; i++) {
    for (var j = 0; j < array2.length; j++) {
      if (array2[j] == array1[i]) {
        console.log("found match: " + array2[j]);
        // counting 
        // count should go up by 1
      }
    }
  }
}

Upvotes: 0

Views: 1999

Answers (3)

Redu
Redu

Reputation: 26161

You may do as follows in O(n);

var arr1   = ["a", "b", "c", "d"],
    arr2   = ["a", "b", "b", "b", "a", "c", "b", "c", "c"],
    result = arr2.reduce((h,p) => (h.hasOwnProperty(p) && h[p]++, h) ,arr1.reduce((m,k) => (m[k] = 0,m),{}));
console.log(result);

Upvotes: 0

Loatheb
Loatheb

Reputation: 62

var array1 = ['a', 'b', 'c', 'd'];
var array2 = ['a', 'b', 'b', 'b', 'a', 'c', 'b', 'c', 'c'];

var result = {}

array1.forEach(function(item) {
    result[item] = 0
})

array2.forEach(function(item) {
    if(result.hasOwnProperty(item)) {
        result[item]++
    }
})
console.log(result);

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

To achieve this you just need to loop through array1 to get the unique values, then you can use filter() to find how many of them exist in the second array. Try this:

var array1 = ['a', 'b', 'c', 'd'];
var array2 = ['a', 'b', 'b', 'b', 'a', 'c', 'b', 'c', 'c'];

var result = {};
array1.forEach(function(item) {
  result[item] = array2.filter(t => t == item).length;
})

console.log(result);

Upvotes: 0

Related Questions