Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  140] [ 3]  / answers: 1 / hits: 70229  / 8 Years ago, fri, may 6, 2016, 12:00:00

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?


More From » arrays

 Answers
123

You can make use of differenceWith() with an isEqual() comparator, and invoke isEmpty to check if they are equal or not.





var isArrayEqual = function(x, y) {
return _(x).differenceWith(y, _.isEqual).isEmpty();
};

var result1 = isArrayEqual(
[{a:1, b:2}, {c:3, d:4}],
[{b:2, a:1}, {d:4, c:3}]
);

var result2 = isArrayEqual(
[{a:1, b:2, c: 1}, {c:3, d:4}],
[{b:2, a:1}, {d:4, c:3}]
);

document.write([
'<div><label>result1: ', result1, '</label></div>',
'<div><label>result2: ', result2, '</label></div>',
].join(''));

<script src=https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.js></script>





UPDATE June 22, 2018



This update is in response to the comment below:




@ryeballar if any of the array is undefined it returns true. How would
you solve this. Thanks in advance buddy




As stated in the differenceWith documentation:




The order and references of result values are determined by the first
array.




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.





var isArrayEqual = function(x, y) {
return _(x).xorWith(y, _.isEqual).isEmpty();
};

var result1 = isArrayEqual(
[{a:1, b:2}, {c:3, d:4}],
[{b:2, a:1}, {d:4, c:3}]
);

var result2 = isArrayEqual(
[{a:1, b:2, c: 1}, {c:3, d:4}],
[{b:2, a:1}, {d:4, c:3}]
);

var result3 = isArrayEqual(
[{a:1, b:2, c: 1}, {c:3, d:4}],
[{b:2, a:1}, {d:4, c:3}, undefined]
);

console.log('result1:', result1);
console.log('result2:', result2);
console.log('result3:', result3);

.as-console-wrapper{min-height:100%;top:0}

<script src=https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js></script>




[#62285] Wednesday, May 4, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;