# How to compare two arrays in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published May 10, 2020. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-compare-arrays

> A short article to learn how to compare two arrays to check if they are equal in vanilla 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()](https://attacomsian.com/blog/json-parse-stringify#jsonstringify) method and then use the comparison operator to check if both strings are equal:

```javascript
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:

```javascript
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](https://lodash.com/docs/4.17.15#isEqual)'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:

```javascript
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](https://attacomsian.com/blog/javascript-arrays) to learn more about JavaScript arrays and how to use them to store multiple values in one variable.
