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

标签 javascript arrays node.js

基本上我有 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/

相关文章:

javascript - 根据特定键随机化 JavaScript 对象数组

javascript - 我只想随机单击某个按钮,然后当我单击“求和”按钮时,它会显示总和

c - 错误 : Cannot convert 'char(*)[a]' to 'char(*)[2]' . 我不明白为什么会出现错误

javascript - Nodejs - Express res.download 发送异常后无法设置 header

javascript - 在 Redux 应用程序中放置模型特定业务逻辑的位置

javascript - Sequelize.js:获取多对多连接模型的关联

php - 我可以在php中自由设置成员吗?

javascript - 如何在 Node js 中返回对 REST api 的响应

node.js - 解构mongodb查询结果返回的对象

javascript - 如何为背景图像上的文本剪切动画