Compare collections in javascript
In testing an API, I wanted to verify not just the response, but also ensure that the desired changes happened in the database. To test, I can compare an expected value of a collection verse a queried value (e.g. Did my code really delete the item).
Use-case
Below are two collections I want to compare. The only thing you need to know is that they are “equal”, but they the two top-most objects are flipped within their arrays. This situation arose from querying my no-sql DB. The order is often unpredictable. I didn’t want to always force an order.
Collection 1
Collection 2
Possible Solutions
Stringify?
Using JSON.stringify()
has potential for comparing most objects. (See this stack overflow post for more info about why you can’t just compare two objects). You would stringify each object then compare the strings. However, since these items are out of order that, will not work.
Library solution
I’m hoping I’m wrong, but I just couldn’t find a library solution (ideally lodash). Unfortuantely, pushing the arrays into _.isEqual()
didn’t work.
A solution for my needs
First step, let’s get these in order. I use lodash’s _.sortBy()
method.
If I get these sorted, then _.isEqual()
will work. Again, no luck. But that’s ok, I can resort to the old stringify trick now that I’m confident in my order.
Here’s my final method:
|
|
Tip: If you break up that return statement, you can choose to log to the console the differing collections upon failure. I find that helpful.