A2oz

How to Check if an Array is Equal to Another Array in JavaScript?

Published in JavaScript 2 mins read

You can check if two arrays are equal in JavaScript using the strict equality operator (===), but only if you're comparing primitive values. For arrays, you need to compare each element individually.

Here's how you can do it:

  1. Using the every() method: This approach iterates through each element of the first array and checks if it's equal to the corresponding element in the second array.

    function arraysEqual(arr1, arr2) {
        if (arr1.length !== arr2.length) {
            return false;
        }
        return arr1.every((element, index) => element === arr2[index]);
    }
  2. Using a loop: This method directly iterates over the arrays and compares elements at each index.

    function arraysEqual(arr1, arr2) {
        if (arr1.length !== arr2.length) {
            return false;
        }
        for (let i = 0; i < arr1.length; i++) {
            if (arr1[i] !== arr2[i]) {
                return false;
            }
        }
        return true;
    }
  3. Using the JSON.stringify() method: This method converts the arrays into JSON strings and compares them directly.

    function arraysEqual(arr1, arr2) {
        return JSON.stringify(arr1) === JSON.stringify(arr2);
    }

Example:

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

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

These methods ensure that the arrays have the same elements in the same order. Remember, the === operator performs a strict equality check, comparing both value and type.

Related Articles