JavaScript: 4 Ways to Compare 2 Arrays

Updated: March 4, 2023 By: Khue Post a comment

This article walks you through 4 different ways to compare 2 given arrays in JavaScript. Of these approaches, there will be some that work well even with complex, deeply nested arrays whose elements are objects or child arrays. Without any further ado, let’s get started.

Using loops

If the arrays you need to compare only contain primitive data types (strings, numbers), this technique is simple and works like a charm. What we will do is use a for loop to iterate through each element of both arrays and compare them one by one. If all elements are equal in both arrays, then we can consider them equal.

Example:

const arr1 = ['blue', 'red', 'green'];
const arr2 = ['blue', 'red', 'green'];

let isEqual = true;

if (arr1.length === arr2.length) {
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      isEqual = false;
      break;
    }
  }
} else {
  isEqual = false;
}

console.log(isEqual); 

Output:

true

Using JSON.stringify() (works with complex arrays)

In cases where you have to deal with arrays that contain objects or subarrays, first, sort them (in descending or ascending order) and then convert both arrays into strings using JSON.stringify() method. After that, you can compare these strings to check whether they are equal or not.

Example:

const arr1 = [
    { id: 1, name: 'Sling Academy' }, 
    { id: 2, name: 'Raging Wolf' }, 
    [1, 2, 3]
];

const arr2 = [
    { id: 2, name: 'Raging Wolf' }, 
    [1, 2, 3], 
    { id: 1, name: 'Sling Academy' }
];

const sortArray = (arr) => {
  return arr.sort((a, b) => {
    if (typeof a === 'object' && typeof b === 'object') {
      return JSON.stringify(a) > JSON.stringify(b) ? 1 : -1;
    }
    return a > b ? 1 : -1;
  });
};

const isEqual =
  JSON.stringify(sortArray(arr1)) === JSON.stringify(sortArray(arr2));

console.log(isEqual); 

Output:

true

Using every() method

This approach is simple and quick, but the downside is that it only works with shallow arrays that contain nothing than primitive data types.

Example:

const arr1 = ['dog', 'cat', 'bird'];
const arr2 = ['dog', 'cat', 'bird'];

const isEqual = arr1.every((element, index) => {
  return element === arr2[index];
});

console.log(isEqual); 

Output:

true

If your use case doesn’t involve complex arrays, this method is a great choice.

Using a recursive function (works with deeply nested arrays)

We can create a recursive function that compares each element of the arrays one by one, even if they contain objects or child arrays. The function checks the length of the arrays and the type of each element and then compares them recursively.

Example:

// define the function 
// that is capable of comparing complex arrays 
function compareArrays(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }

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

  return true;
}

// define a function 
// that is capable of comparing objects
function compareObjects(obj1, obj2) {
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (let i = 0; i < keys1.length; i++) {
    const key = keys1[i];
    if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) {
      if (!compareArrays(obj1[key], obj2[key])) {
        return false;
      }
    } else if (typeof obj1[key] === 'object' && typeof obj2[key] === 'object') {
      if (!compareObjects(obj1[key], obj2[key])) {
        return false;
      }
    } else if (obj1[key] !== obj2[key]) {
      return false;
    }
  }

  return true;
}

// test the function
const arr1 = [{ a: 1, b: [2, 3] }, { c: { d: 4 } }];
const arr2 = [{ a: 1, b: [2, 3] }, { c: { d: 4 } }];
console.log(compareArrays(arr1, arr2)); 
// Expected output: true

const arr3 = [{ a: 1, b: [2, 3] }, { c: { d: 4 } }];
const arr4 = [{ a: 1, b: [2, 3] }, { c: { d: 5 } }];
console.log(compareArrays(arr3, arr4)); 
// Expected output: false

const arr5 = [{ a: 1, b: [2, { c: [3, 4] }] }, { d: { e: 5 } }];
const arr6 = [{ a: 1, b: [2, { c: [3, 4] }] }, { d: { e: 5 } }];
console.log(compareArrays(arr5, arr6)); 
// Expected output: true

const arr7 = [{ a: 1, b: [2, { c: [3, 4] }] }, { d: { e: 5 } }];
const arr8 = [{ a: 1, b: [2, { c: [3, 5] }] }, { d: { e: 5 } }];
console.log(compareArrays(arr7, arr8)); 
// Expected output: false

Output:

true
false
true
false

This method seems to be tough and may need to be customized on a case-by-case basis. It’s also quite a bit longer than using JSON.stringify().

Conclusion

We’ve covered 4 distinct ways to compare arrays in modern JavaScript. Depending on your use case, choose from them the one that fits. If you want to dig deeper into complex object comparison (mentioned a bit in the last example), check out this article: A few Ways to Compare 2 Objects in JavaScript.