1

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.

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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 ] )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.