Check if values of two arrays are the same/equal in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have two arrays of numbers, let’s say −

[2, 4, 6, 7, 1]
[4, 1, 7, 6, 2]

Assume, we have to write a function that returns a boolean based on the fact whether or not they contain the same elements irrespective of their order.

For example −

[2, 4, 6, 7, 1] and [4, 1, 7, 6, 2] should yield true because they have the same elements but ordered differently.

Now, let’s write the code for this function −

Example

const first = [2, 4, 6, 7, 1];
const second = [4, 1, 7, 6, 2];
const areEqual = (first, second) => {
   if(first.length !== second.length){
      return false;
   };
   for(let i = 0; i < first.length; i++){
      if(!second.includes(first[i])){
         return false;
      };
   };
   return true;
};
console.log(areEqual(first, second));

Output

The output in the console will be −

true
raja
Published on 24-Aug-2020 09:10:05
Advertisements