gpt4 book ai didi

javascript - 对象数组与lodash的深度比较

转载 作者:可可西里 更新时间:2023-11-01 01:46:07 32 4
gpt4 key购买 nike

我有 2 个对象数组,我将与 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 } ]

我应该如何比较才能看到两者相等?

最佳答案

您可以使用 differenceWith()isEqual()比较器,并调用 isEmpty检查它们是否相等。

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 日更新

此更新是对以下评论的回应:

@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 调用的结果数组将为空。

真正解决问题的另一种解决方案是使用 xorWith()具有与上述解决方案相同的功能链。

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>

关于javascript - 对象数组与lodash的深度比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37065663/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com