Easy Way to Check if 2 Arrays are Equal in JavaScript

Easy Way to Check if 2 Arrays are Equal in JavaScript

Works with comparing 2 Objects too....

·

2 min read

When learning JavaScript for the first time we've all done this...

const a = [1,2];
const b = [1,2];

if (a === b) console.log('Equal!');

If you'd tried this, then you KNOW a === b will return false every time.

Why is that?

Because array variables are assigned by reference NOT by value.

So a is just a pointer to the location of [1,2] somewhere in memory. While 'b' is another pointer to a different location in memory, that also happens to be storing [1,2].

When you're checking if a === b, you're really checking their member locations, and not the values they're pointing to.

So what gives?

Is there any easy way to check if the underlying arrays that are represented by a and b are equal, WITHOUT having to do an element by element comparison?

Here's the quick cheat to get it done...

const d = [1,2,4,5,6];
const c = [1,2,4,5,6];

if (JSON.stringify(d) === JSON.stringify(c)) console.log('Equal!');

Why does this work?

And what the heck is JSON.stringify(...) anyway?

JSON.stringify(...) takes an array (or an object)and returns its string representation.

It's stringified!

For example:

JSON.stringify([7,8,9])

Will just return '[7,8,9]'. Since the value is a string, you can compare it with the value of another array, that's also returned as a string with JSON.stringify(...). :)

This trick even works with double array (and multi-dimensional arrays in general). You can also compare objects this way, as long as properties of each object are in the same order.

Another Tip

If you want to compare if 2 arrays contain the same values, regardless of order, then just use Array.sort() method to sort both arrays first, THEN use JSON.stringify to compare then!

Did you find this article valuable?

Support Indepth JavaScript by becoming a sponsor. Any amount is appreciated!