function union(a, b) {
const end = b.length - 1
const has = (key) => {
let i = end
while (i--) if (b[i].Key === key) return true
return false
}
for (const item of a) {
has(item.Key) || b.push(item)
}
}
const A = [{key: 1}, {key: 2}, {key: 3}];
const B = [{key: 3}, {key: 4}, {key: 5}];
const bKeys = new Set(B.map(({ key }) => key));
for (const el of A) {
if (!bKeys.has(el.key)) B.push(el);
}
console.log(B);
UP(双打+古代JS):
为了不创建新数组(也不过滤)并且不检查每个元素,我们使用 has() 检查,仅 B 个元素
如果数组很大,@Darth 的答案可以稍微优化一下时间。让我们使用正在检查的数组中的键创建一个辅助
Set项,这样我们就不必在每次迭代中搜索它。但是您需要检查特定情况,以便创建时间Set不会抵消进一步的收益。