gpt4 book ai didi

javascript - lodash - 使用 IntersectionWith 获取对象数组的交集会导致唯一性问题

转载 作者:行者123 更新时间:2023-12-01 03:03:03 24 4
gpt4 key购买 nike

我正在尝试使用 Lodash intersectWith 通过某些属性来相交 2 个对象数组。

例如:

var objects = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

// Intersect by objects with the same value for 'x'
_.intersectionWith(objects, others, (obj, oth) => obj.x === oth.x);

这样做,我只得到了 1 个对象的意外结果:

[{ x: 1, y: 1 }]

而不是整个第一个数组:

[{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]

出于某种原因,intersectionWith 函数似乎只根据所比较的属性返回唯一的结果。

谁能解释一下为什么会发生这种情况?

最佳答案

也许你错过了 _.intersection 的部分:

Creates an array of unique values that are included in all given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array. [Emphasis by NS]

这意味着,如果您检查的值为 x: 1,则结果集中不再包含具有该值的对象。

关于javascript - lodash - 使用 IntersectionWith 获取对象数组的交集会导致唯一性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46352212/

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