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.
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
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
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(...) takes an array (or an object)and returns its string representation.
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
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.
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 Amit Mehta by becoming a sponsor. Any amount is appreciated!