Comparing array elements keeping count in mind in JavaScript


Suppose, we have two arrays of literals that contain the same number of elements. We are supposed to write a function that checks whether or not the both arrays contain the same elements appearing for the same number of times.

If the arrays fulfil this condition, we return true, false otherwise.

We will create a copy of the second array, and start iterating over the first array. As we iterate, we will keep deleting the elements from the second array that are present in first array. If during iteration we encounter any element that isn't present in second array, we return false. Otherwise, at the end of iteration we will return true.

Example

The code for this will be −

const arr1 = [2, 5, 7, 4, 3, 3];
const arr2 = [3, 5, 7, 2, 3, 4];
const compareWithCount = (arr1, arr2) => {
   if(arr1.length !== arr2.length){
      return false;
   };
   const copy2 = arr2.slice();
   const areEqual = arr1.every(el => {
      if(!copy2.includes(el)){
         return false;
      };
      copy2.splice(copy2.indexOf(el), 1);
      return true;
   });
   return areEqual;
};
console.log(compareWithCount(arr1, arr2));

Output

And the output in the console will be −

true

Updated on: 20-Nov-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements