This post will discuss how to compare arrays in JavaScript. Two arrays are said to be equal if they have the same elements in the same order. The solution should work for nested arrays of any depth.

For example, the array [1, 2, [3, [4, 5]]] is equal to the array [1, 2, [3, [4, 5]]] while it is different from the array [1, 2, [3, 4, 5]].

1. Using Underscore/Lodash Library

If you’re already using the Underscore or Lodash library, consider using the _.isEqual method to test for array equality. It performs a deep comparison between specified values and also works for nested arrays.

Download Code

2. Using JSON.stringify() function

Another solution is to convert both arrays into a JSON string and compare their string representation with each other to determine equality. For converting the array to a JSON string, you can use the JSON.stringify() method. This is demonstrated below:

Download  Run Code

 
The above solution might not work if your array contains a nullish value (i.e., null or undefined) or another object but works fine for other primitive values like numbers and strings.

3. Custom function

Finally, you can write custom logic to determine whether two arrays are equivalent. The following code example shows how to implement this.

Download  Run Code

4. Using String.prototype.toString() function

For a primitive array of numbers and strings, you can simply call toString():

Download  Run Code

 
Alternatively, use the Array.prototype.every() to compare each array element with elements of the other array.

Download  Run Code

That’s all about comparing arrays in JavaScript.