gpt4 book ai didi

javascript - A 在 B 中与函数式编程的相对补充

转载 作者:行者123 更新时间:2023-11-29 10:30:09 24 4
gpt4 key购买 nike

我必须检索仅存在于数组 B 中但不存在于数组 A 中的值。

根据我的研究,它被称为:

relative complement of A in B

enter image description here

数组中的值可能不是原始值。我需要一个有效且实用的方法来解决这个问题。我找到了 lodash _.without函数,但它仅支持原始数字数组。

数组A:

[{
id: 1
},
{
id:2
}]

数组 B:

[{
id:2
},
{
id:3
}]

结果应该是:

[{
id:3
}]

此对象是唯一存在于数组 B 上但不存在于数组 A 上的对象。

最佳答案

您可以使用一个比较函数,它接受两个对象并检查 id 是否不相等。

var aa = [{ id: 1 }, { id: 2 }],
bb = [{ id: 2 }, { id: 3 }],
comparison = (a, b) => a.id !== b.id,
result = bb.filter(b => aa.every(a => comparison(a, b)));

console.log(result);

检查是否相等

var aa = [{ id: 1 }, { id: 2 }],
bb = [{ id: 2 }, { id: 3 }],
comparison = (a, b) => a.id === b.id,
result = bb.filter(b => aa.every(a => !comparison(a, b)));

console.log(result);

关于javascript - A 在 B 中与函数式编程的相对补充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48259302/

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