Open In App

JavaScript- Arrays are Equal or Not

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following approaches to compare two arrays in JavaScript:

1. Using the JSON.stringify() Method

JavaScript provides a function JSON.stringify() method in order to convert an object whether or array into a JSON string. By converting it into JSON strings, we can directly check if the strings are equal or not.

JavaScript
let a1 = [1, 2, 3, 5];
let a2 = [1, 2, 3, 5];

if (JSON.stringify(a1) == JSON.stringify(a2))
    console.log("True");
else
    console.log("False");

Output
True
False

2. Using JavaScript for Loop

In this method, we will compare each element of the array one by one using for loop. we manually check each and every item and return true if they are equal otherwise return false.

JavaScript
let a = [1, 2, 3, 5];
let b = [1, 2, 3, 5];

// If length is not equal
if (a.length != b.length)
    console.log(false);
else {

    // Comparing each element of array
    for (let i = 0; i < a.length; i++)
        if (a[i] != b[i])
            return console.log(false);
    ;
    return console.log(true);
}

Output
True

3. String Comparison

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.

JavaScript
let a = [1, 2, 3, 5];
let b = [1, 2, 3, 5];
let res = a.join() == b.join();
console.log(res);

Output
true

4. Using Array every() Method

The Javascript Array.every() method considers all the elements of an array and then further checks whether all the elements of the array satisfy the given condition (passed by in user) or not that is provided by a method passed to it as the argument.

JavaScript
const compareFunc = (a, b) =>
    a.length === b.length &&
    a.every((element, index) => element === b[index]);

let a = [1, 2, 3, 5];
let b = [1, 2, 3, 5];
console.log(compareFunc(a, b)); 

Output
true

5. Using Lodash _.isEqual() Method

In this approach, we are using the Lodash _.isEqual() method that return boolean value of the result whether that given arrays are equal or not.

JavaScript
// Defining Lodash variable 
const _ = require('lodash');

let a1 = [1, 2, 3, 4]

let a2 = [1, 2, 3, 4]

// Checking for Equal Value 
console.log("The Values are Equal : "
    + _.isEqual(a1, a2));

Output:

The Values are Equal : true

6. Using Set

The Set object in JavaScript allows you to store unique values of any type, including arrays. By converting arrays to sets, you can easily compare them, as sets automatically remove duplicate values.

JavaScript
function compareArrays(a1, a2) {
    const s1 = new Set(a1);
    const s2 = new Set(a2);

    if (s1.size !== s2.size) {
        return false;
    }

    for (const item of s1) {
        if (!s2.has(item)) {
            return false;
        }
    }

    return true;
}

const a1 = [1, 2, 3, 4];
const a2 = [4, 3, 2, 7];

console.log(compareArrays(a1, a2)); 

Output
true

7. Using reduce and some Methods

This method involves reducing the arrays into an object that keeps track of the elements and their counts, then comparing these objects.

JavaScript
function arraysEqual(a1, a2) {
    if (a1.length !== a2.length) return false;

    let countElements = (arr) =>
        arr.reduce((acc, val) => {
            acc[val] = (acc[val] || 0) + 1;
            return acc;
        }, {});

    let c1 = countElements(a1);
    let c2 = countElements(a2);

    return !Object.keys(c1).some(key => c1[key] !== c2[key]);
}

let a1 = [1, 2, 3, 4];
let a2 = [4, 3, 2, 1];
let a3 = [1, 2, 3, 5];

console.log(arraysEqual(a1, a2));
console.log(arraysEqual(a1, a3)); 

Output
true
false

8. Using Array.prototype.sort() Method

This approach leverages the fact that two arrays are equal if they contain the same elements in the same order. By sorting both arrays and then comparing them element by element, we can determine if they are equal. This method is particularly useful for comparing arrays where the order of elements does not matter.

JavaScript
function arraysEqual(a1, a2) {
    if (a1.length !== a2.length) return false;

    let s1 = a1.slice().sort();
    let s2 = a2.slice().sort();

    for (let i = 0; i < s1.length; i++) {
        if (s1[i] !== s2[i]) return false;
    }
    return true;
}
let a1 = [3, 1, 2];
let a2 = [2, 3, 1];

console.log(arraysEqual(a1, a2)); 

Output
true

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Next Article

Similar Reads