=== only returns
true if the arrays are the same reference.
In cases like this, it helps to be as explicit as possible about what you mean by “equal.” In software engineering, asking a question in the right way often makes the answer obvious.
With that in mind, here’s 3 definitions of equality for arrays and how to check them.
Same Length, Each Value Equal
One approach for comparing
b is checking if each value of
a is strictly equal to the corresponding value of
b. This works well if all the elements of the arrays are primitives as opposed to objects.
Deep Equality With POJOs
arrayEquals() function works great for primitive values, but falls short if you want to compare objects by value.
One neat way to take into account object values is comparing arrays by their
This approach is handy because it requires minimal code and no outside libraries. However, comparing
JSON.stringify() output has an unfortunate edge case that may be a problem depending on your use case. Since
undefined isn’t a valid JSON value, the below arrays have the same
JSON.stringify() output, because
In addition to the
undefined quirk, comparing
JSON.stringify() output also doesn’t take into account object types. As far as
JSON.stringify() is concerned, an object with a
toJSON() function that returns 42 is the same as the number 42.
Similarly, a custom object is the same as a POJO:
isEqual() function, on the other hand, takes all this into account.
isEqual() function is the way to go if you need all the bells and whistles of checking that objects have the same class. The
JSON.stringify() approach works well for POJOs, just make sure you take into account
null and only use it with trusted data –
toJSON() can be a security vulnerability.