A2oz

How Do You Deep Compare Two Arrays in JavaScript?

Published in JavaScript 3 mins read

Deep comparison, also known as recursive comparison, involves checking if two arrays have the same elements, including nested objects or arrays, at every level. This goes beyond a simple comparison of array lengths or shallow equality.

Methods for Deep Comparison

Here are some methods to achieve deep comparison of arrays in JavaScript:

1. Using JSON.stringify()

This method converts the arrays into JSON strings and then compares them.

Code Example:

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

const arr1 = [1, { a: 2 }, [3, 4]];
const arr2 = [1, { a: 2 }, [3, 4]];

console.log(deepCompare(arr1, arr2)); // true

Advantages:

  • Simple and straightforward.

Disadvantages:

  • Doesn't work for circular references or objects with methods.
  • Can be inefficient for large arrays.

2. Recursive Function Approach

This method involves writing a recursive function that iterates through each element of the arrays and compares them using a deep comparison.

Code Example:

function deepCompare(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i = 0; i < arr1.length; i++) {
    if (typeof arr1[i] === 'object' && typeof arr2[i] === 'object') {
      if (!deepCompare(arr1[i], arr2[i])) {
        return false;
      }
    } else if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}

const arr1 = [1, { a: 2 }, [3, 4]];
const arr2 = [1, { a: 2 }, [3, 4]];

console.log(deepCompare(arr1, arr2)); // true

Advantages:

  • Handles nested objects and arrays.
  • More flexible than JSON.stringify().

Disadvantages:

  • Can be more complex to implement.
  • Can be inefficient for large arrays.

3. Using Third-party Libraries

Libraries like lodash provide dedicated functions for deep comparison, making the process easier and often more efficient.

Code Example:

const _ = require('lodash');

const arr1 = [1, { a: 2 }, [3, 4]];
const arr2 = [1, { a: 2 }, [3, 4]];

console.log(_.isEqual(arr1, arr2)); // true

Advantages:

  • Provides a convenient and well-tested solution.
  • Often optimized for performance.

Disadvantages:

  • Requires installing an external library.

Practical Insights

  • Choose the method that best suits your specific needs and the complexity of your arrays.
  • Consider performance implications for large arrays.
  • Be aware of the limitations of JSON.stringify(), especially with circular references and objects with methods.

Conclusion

Deep comparison of arrays in JavaScript allows for a thorough check of equality, considering nested objects and arrays. Choose the method that best fits your requirements and prioritize efficiency for large arrays.

Related Articles