Equality of two arrays JavaScript


We are required to write a JavaScript function that takes in two arrays of Numbers, say first and second and checks for their equality.

Equality in our case will be determined by one of these two conditions −

  • The arrays are equal if they contain the same elements irrespective of their order.

  • If the sum of all the elements of the first array and second array is equal.

For example −

[3, 5, 6, 7, 7] and [7, 5, 3, 7, 6] are equal arrays
[1, 2, 3, 1, 2] and [7, 2] are also equal arrays
but [3, 4, 2, 5] and [2, 3, 1, 4] are not equal

Let's write the code for this function −

Example

const first = [3, 5, 6, 7, 7];
const second = [7, 5, 3, 7, 6];
const isEqual = (first, second) => {
   const sumFirst = first.reduce((acc, val) => acc+val);
   const sumSecond = second.reduce((acc, val) => acc+val);
   if(sumFirst === sumSecond){
      return true;
   };
   // do this if you dont want to mutate the original arrays otherwise use
   first and second
   const firstCopy = first.slice();
   const secondCopy = second.slice();
   for(let i = 0; i < firstCopy.length; i++){
      const ind = secondCopy.indexOf(firstCopy[i]);
      if(ind === -1){
         return false;
      };
      secondCopy.splice(ind, 1);
   };
   return true;
};
console.log(isEqual(first, second));

Output

The output in the console will be −

true

Updated on: 31-Aug-2020

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements