gpt4 book ai didi

javascript - 有效匹配数组,将找到的键放入第二个数组

转载 作者:行者123 更新时间:2023-11-30 19:34:59 24 4
gpt4 key购买 nike

基本上我有 2 个数组。生成的 unmatched 数组有重复项,一旦找到它就应该将项目丢弃在数组中,这将导致 countB 变量在完成后变小并且没有重复项 unmatched 数组

const arr1 = ['Bill', 'Bob', 'John'];
const arr2 = ['Bill', 'Jane', 'John'];
const matched = [];
const unmatched = [];
countA = 0;
countB = 0;
/* Result expected
matched = [Bill, John]
unmatched = [Bob, Jane] */

arr1.forEach((e1) => {
countA++;
for (const e2 of arr2) {
countB++;
if (e1 == e2) {
matched.push(e1);
break;
} else {
unmatched.push(e2);
}
}
});
console.log("unmatched",unmatched);
console.log("matched", matched);
console.log(`Counts ForEach Loop A:${countA} For In Loop B:${countB}`);

预期的结果是两个数组:

    matched = [Bill, John]
    unmatched = [Bob, Jane]

最佳答案

你可以拿一个Set并检查第二个数组的实际值是否在集合中。根据需要获取数组并将元素推送到它。

const
array1 = ['Bill', 'Bob', 'John'],
array2 = ['Bill', 'Jane', 'John'],
set1 = new Set(array1),
matched = [],
unmatched = [];

array2.forEach(v => (set1.delete(v) ? matched : unmatched).push(v));
unmatched.push(...set1);

console.log(matched);
console.log(unmatched);

关于javascript - 有效匹配数组,将找到的键放入第二个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56040401/

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