VIK6Galado
VIK6Galado

Reputation: 680

How to check number of occurrence for an item is same in 2 different arrays in javascript?

I have 2 array as shown below:

arr1 = [a,b,c,a,c,b,a] arr2 = [b,b,a,a,a,b,c]

I am checking the number of occurrence of each item in both arrays are same

for e.g. a is count in arr1 and arr2 is 3. like wise want to check for rest of the items if it is same the continue or break the loop

      for(let i=0; i < this.arr1.length; i++){
        for(let j=0; j < this.arr2.length; j++){
          if(this.arr1[i] === this.arr2[j]){
            let count1 = this.arr1.filter((t) => {
              return t == this.arr1[i];
            });

            let count2 = this.arr2.filter((e) => {
              return e == this.arr2[j];
            });

            if(count1.length !== count2.length){
              // break the loops and return false
            }
          }
        }
      }  

Above code is not working correctly. where am i doing wrong.

Upvotes: 1

Views: 50

Answers (2)

gurvinder372
gurvinder372

Reputation: 68393

Get count map of each of the array and then compare the map

var fnGetCountMap = arr => arr.reduce( ( acc, c ) => {
   acc[ c ] = (acc[ c ] || 0) + 1; 
   return acc;
} , {} )

Now get the count-map for each array and compare

var countMapArray1 = fnGetCountMap( arr1 );
var countMapArray2 = fnGetCountMap( arr2 );

For simple comparison (to tell if they are equal)

 return JSON.stringify( countMapArray1 ) == JSON.stringify( countMapArray2 );

To tell which value has different frequency

Object.keys( countMapArray1 ).filter( s => countMapArray1[ s ] != countMapArray2[ s ] )

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could use a hash table and count up for one array and down for the other and take only the keys which values are not zero.

var array1 = ['a', 'b', 'c', 'a', 'c', 'b', 'a'],
    array2 = ['b', 'b', 'a', 'a', 'a', 'b', 'c'],
    count = Object.create(null),
    result;
    
array1.forEach(a => count[a] = (count[a] || 0) + 1);
array2.forEach(a => count[a] = (count[a] || 0) - 1);

result = Object.keys(count).filter(k => count[k]);

console.log(result);
console.log(count);

Upvotes: 2

Related Questions