In this article I will discuss 10 different methods to compare two arrays in JavaScript, taking into account various factors such as order and nested structures.

In JavaScript, comparing arrays can be tricky, as the language handles array comparisons by reference instead of by value.

By the end of this article, you will have a better understanding of how to compare two arrays in JavaScript effectively and accurately.

1. Equality Comparison

In JavaScript, arrays are compared by reference, not by value. Therefore, using the strict equality operator (===) or the loose equality operator (==) will result in false even if both arrays contain the same elements in the same order. This method is not recommended for comparing arrays.

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

console.log(a === b); // false

2. JSON.stringify()

This method converts each array into a JSON string using JSON.stringify(), and then compares the two strings.

It’s a simple and straightforward solution but has some edge cases where it may produce incorrect results.

For example, when comparing values with different types, the serialized strings might be the same, leading to a false positive.

const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b);

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

console.log(equals(a, b)); // true

3. Comparing Length and Values

This method first checks if the two arrays have the same length, and then uses Array.prototype.every() to compare each corresponding element in both arrays. It avoids the edge cases present in the JSON.stringify() method but does not handle nested arrays or objects.

const equals = (a, b) =>
  a.length === b.length &&
  a.every((v, i) => v === b[i]);

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

console.log(equals(a, b)); // true

4. Handling Nested Arrays

This method uses a recursive function to compare arrays with nested arrays or objects. It first checks if the two arrays have the same length, and then iterates through each element. If both elements are arrays, the function calls itself recursively; otherwise, it compares the elements directly.

function deepEquals(a, b) {
  if (a.length !== b.length) return false;

  for (let i = 0; i < a.length; i++) {
    if (Array.isArray(a[i]) && Array.isArray(b[i])) {
      if (!deepEquals(a[i], b[i])) return false;
    } else if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}

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

console.log(deepEquals(a, b)); // true

5. lodash isEqual()

The lodash library provides a utility function called isEqual() that can compare arrays, including nested arrays and objects. It is a robust and reliable solution for comparing arrays in most use cases.

const _ = require('lodash');

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

console.log(_.isEqual(a, b)); // true

6. Comparing Arrays Regardless of Order

This method is used when the order of the elements in the arrays is not important.

It first checks if the two arrays have the same length, then iterates through unique values using Set.

For each unique value, it counts the occurrences in both arrays and compares the counts.

const equalsIgnoreOrder = (a, b) => {
    if (a.length !== b.length) return false;
    const uniqueValues = new Set([...a, ...b]);
    for (const v of uniqueValues) {
        const aCount
        const aCount = a.filter(e => e === v).length;
        const bCount = b.filter(e => e === v).length;
        if (aCount !== bCount) return false;
    }
    return true;
};

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

console.log(equalsIgnoreOrder(a, b)); // true

7. Using Array.prototype.sort()

This method sorts both arrays using Array.prototype.sort() and then compares their elements in order. It first checks if the arrays have the same length, then sorts a copy of each array, and finally uses Array.prototype.every() to compare corresponding elements.

const sortedEquals = (a, b) => {
  if (a.length !== b.length) return false;
  const sortedA = a.slice().sort();
  const sortedB = b.slice().sort();
  return sortedA.every((v, i) => v === sortedB[i]);
};

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

console.log(sortedEquals(a, b)); // true

8. Set and Array.from()

This method uses Set to create a set of unique values from both arrays and then checks if the size of both sets is the same. It then uses Array.from() to create an array from the set and checks if every value in the first set is present in the second set using Set.prototype.has()

const uniqueEquals = (a, b) => {
  const setA = new Set(a);
  const setB = new Set(b);
  return setA.size === setB.size && Array.from(setA).every(value => setB.has(value));
};

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

console.log(uniqueEquals(a, b)); // true

9. Using Array.prototype.reduce()

This method creates frequency maps of both arrays using Array.prototype.reduce(). It then iterates through the keys in the first map and compares the corresponding frequency values in both maps. If there is any mismatch, it returns false; otherwise, it returns true.

const frequencyEquals = (a, b) => {
  if (a.length !== b.length) return false;

  const frequencyMap = (arr) =>
    arr.reduce((acc, v) => {
      acc[v] = (acc[v] || 0) + 1;
      return acc;
    }, {});

  const freqA = frequencyMap(a);
  const freqB = frequencyMap(b);

  for (const key in freqA) {
    if (freqA[key] !== freqB[key]) return false;
  }

  return true;
};

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

console.log(frequencyEquals(a, b)); // true

10. Using Map and Array.prototype.forEach()

This method first creates a Map to store the frequency of elements in both arrays. It then iterates through each array using Array.prototype.forEach() and updates the frequency count in the map. After iterating through both arrays, it checks if all the frequency counts in the map are zero, indicating that the arrays have the same elements regardless of order.

const mapEqualsIgnoreOrder = (a, b) => {
  if (a.length !== b.length) return false;

  const map = new Map();
  a.forEach(e => map.set(e, (map.get(e) || 0) + 1));
 b.forEach(e => map.set(e, (map.get(e) || 0) - 1));

return Array.from(map.values()).every(count => count === 0);
};

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

console.log(mapEqualsIgnoreOrder(a, b)); // true

Conclusion

These 10 methods demonstrate different ways to compare arrays in JavaScript. Some methods are more suitable for specific use cases, while others provide more general solutions. It’s essential to understand the strengths and weaknesses of each method and choose the most appropriate one for your specific requirements. When using these methods, remember to test them with various input scenarios, including edge cases, to ensure their accuracy and robustness.