对象数组与 lodash 的深度比较 [英] Array of object deep comparison with lodash
问题描述
我有 2 个对象数组,可以与 lodash
I've 2 array of objects that I'd deeply compare with lodash
但是,我有一个问题:
> 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?
推荐答案
你可以使用 differenceWith() 使用 isEqual() 比较器,并调用 isEmpty 检查它们是否相等.
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>
2018 年 6 月 22 日更新
此更新是对以下评论的回应:
This update is in response to the comment below:
@ryeballar 如果任何数组未定义,则返回 true.怎么会你解决这个.提前谢谢哥们
@ryeballar if any of the array is undefined it returns true. How would you solve this. Thanks in advance buddy
如 differenceWith
文档中所述:
结果值的顺序和引用由第一个决定数组.
The order and references of result values are determined by the first array.
这意味着只要第一个数组中的所有项都匹配第二个数组中的所有其他项,则 differenceWith
调用的结果数组将为空.
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.
真正解决问题的另一种解决方案是使用xorWith()
具有与上述解决方案相同的功能链.
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>
这篇关于对象数组与 lodash 的深度比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!