I've 2 array of objects that I'd deeply compare with lodash
However, I've a prob with it:
> var x = [{a:1, b:2}, {c:3, d:4}];
> var y = [{b:2, a:1}, {d:4, c:3}];
> _.difference(x,y, _.isEqual);
[ { a: 1, b: 2 }, { c: 3, d: 4 } ]
How should I compare to see that both are equal?
I prefer pure JS since i haven't got the patience to learn underscore or lodash. So i invent something i have been long dreaming of. The
Object.prototype.compare()
. The v0.0.2 is doing only shallow comparison though but adequate for this question.Cool... So then lets continue with the question... I guess... since we already have an
Object.prototype.compare()
there should be absolutely no harm in the invention ofArray.prototype.compare()
. Lets make it more clever this time. It shall tell primitives from objects. One other thing is, arrays are ordered; so in my book[1,2]
is not equal to[2,1]
. Also this makes the job simpler.You can make use of differenceWith() with an isEqual() comparator, and invoke isEmpty to check if they are equal or not.
UPDATE June 22, 2018
This update is in response to the comment below:
As stated in the
differenceWith
documentation:This means that as long as all the items in the first array will match everything else in the second array, then the resulting array from the
differenceWith
invocation will be empty.An alternative solution that truly solves the problem is to use
xorWith()
with the same chain of functions from the solution above.