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.

Method 1: Using includes() and Length Check

This approach checks if both arrays have the same length and every element from the first array exists in the second array.

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 

true
true
false

Method 2: Using Sort and JSON.stringify

This method sorts both arrays and compares their string representations.

const areEqualSorted = (first, second) => {
    if(first.length !== second.length) return false;
    return JSON.stringify(first.sort()) === JSON.stringify(second.sort());
};

const arr1 = [3, 1, 4, 2];
const arr2 = [2, 4, 1, 3];
const arr3 = [1, 2, 3, 5];

console.log(areEqualSorted(arr1, arr2));
console.log(areEqualSorted(arr1, arr3));
true
false

Method 3: Using every() Method

A more functional approach using the every() method to check if all elements exist in both arrays.

const areEqualEvery = (first, second) => {
    return first.length === second.length && 
           first.every(element => second.includes(element));
};

const x = [5, 3, 8, 1];
const y = [1, 8, 3, 5];
const z = [5, 3, 8];

console.log(areEqualEvery(x, y));
console.log(areEqualEvery(x, z));
true
false

Handling Duplicate Elements

The above methods work for arrays with unique elements. For arrays with duplicates, we need a different approach:

const areEqualWithDuplicates = (first, second) => {
    if(first.length !== second.length) return false;
    
    const firstCopy = [...first];
    const secondCopy = [...second];
    
    return JSON.stringify(firstCopy.sort()) === JSON.stringify(secondCopy.sort());
};

const a = [1, 2, 2, 3];
const b = [2, 1, 3, 2];
const c = [1, 2, 3, 3];

console.log(areEqualWithDuplicates(a, b));
console.log(areEqualWithDuplicates(a, c));
true
false

Performance Comparison

Method Time Complexity Handles Duplicates Modifies Original
includes() method O(n²) No No
Sort + stringify O(n log n) Yes Yes (if not copied)
every() method O(n²) No No

Conclusion

For arrays with unique elements, the every() method provides clean, readable code. For arrays with duplicates or better performance, use the sort and stringify approach with array copies to avoid modifying originals.

Updated on: 2026-03-15T23:18:59+05:30

698 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements