How to compare two arrays in JavaScript

published: 03 Apr 2022

2 min read

How to compare two arrays in JavaScript

In vanilla JavaScript, unfortunately, there is no direct method available to compare two arrays to check if they are equal. If you Google this, you'll find a lot of different answers on StackOverflow and other developer communities.

When comparing two arrays, you have to make sure that their length is the same, the values are identical, and the objects present in them are of the same type.

JSON.stringify() Method

The simplest and fastest way to compare two arrays is to convert them to strings by using the JSON.stringify() method and then use the comparison operator to check if both strings are equal:

const arr1 = ['🍕', '🍔', '🍵', '🎂', '🍦'];
const arr2 = ['🍕', '🍔', '🍵', '🎂', '🍦'];

// compare arrays
if (JSON.stringify(arr1) === JSON.stringify(arr2)) {
    console.log('Both arrays are equal!');
} else {
    console.log('Arrays are not equal.');
}

This approach is good for only basic comparison when the elements in both arrays have the exact same order. If the order of the elements is different in both arrays, it won't work.

For example, the following two arrays would not be equal using the JSON.stringify() method:

const arr1 = ['a', 'b', 'c', 'd'];
const arr2 = ['a', 'c', 'b', 'd'];

JSON.stringify(arr1) === JSON.stringify(arr2); // false

The above two arrays contain the same number of elements and the exact same values but in a different order. Hence, they are not equal when compared through JSON.stringify().

Lodash

For complex arrays that contain elements in a different order as well as other arrays and objects, we need a more robust solution like the Lodash's _.isEqual() method.

The _.isEqual() method performs a deep comparison between two arrays to determine if they are equivalent. You can even use it to perform a comparison between objects, dates, strings, array buffers, and more.

Here is an example:

const arr1 = ['John Doe', {age: 24, nationality: 'DE'}];
const arr2 = ['John Doe', {nationality: 'DE', age: 24}];

// compare arrays
if (_.isEqual(arr1, arr2)) {
    console.log('Arrays are equal!');
}

Take a look at this guide to learn more about JavaScript arrays and how to use them to store multiple values in one variable.

How to compare two arrays in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array