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



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
Updated on: 2020-08-24T09:10:59+05:30

652 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements