Yesterday, we looked at a way to tell if two arrays are equal with JavaScript. The approach is fast and simple, but falls apart pretty quickly for all but the most basic of arrays. Show Today, we’re going to look at a much more robust way to compare two arrays (or objects) and check if they’re equal to each other. What we need to compareYou could have a simple array, like this one.
Or, you could have a complex, multidimensional array with various types of inputs.
To properly compare two arrays or objects, we need to check:
And if the item is itself an array or object, we need to compare all of its values against that same items values in the other array or object. To make this all work, we’re going to create a helper function to test all of these things. Let’s get started… Setting up our helper functionLet’s create a helper function called We’ll accept two arguments: the
We’re going to run a series of tests in our helper function. If at any point one of them fails, we’ll immediately If at the end the function is still running, it means all of our tests and comparisons passed and we can
Some basic testsThere are a few basic tests we can run right away to quickly eliminate any arrays or objects that obviously aren’t equal. First, if
Next, we want to make sure our two items are either an object or an array. Our function won’t really be setup to compare strings, functions, and so on. We’ll use
Finally, if our two arrays or objects have a different number of items in them, they’re not equal. You can easily get the value of an array using
We’ll create variables for the length of both
Comparing item valuesNow that we’ve got some basic checks out of the way, we can start comparing the values of the items in our array or object. To start, we want to loop through each item in our
We’re going to compare the items the same way whether it’s an object or an array, and we don’t want to write the same code twice. Let’s set up a We’ll pass in either the
Comparing two itemsFirst, let’s get the type for our item. We’ll need this information more than once, so let’s set it to the If it’s an array or object, we’ll pass it back into the
If it’s not
an array or object, we’ll do a simple comparison to check our two item values. First, we’ll make sure that
Now, we can compare are two values using a simple We need to account for one last edge case, though. If the item is a function, we need to convert it to a string using the
Getting the value of our compare() functionAs we loop through each item and compare it, we need to check if our (The
Putting it all togetherWe can now
test two objects or arrays to see if they’re equal by passing them in to our
Here’s the complete helper function.
|