javascript - 检查 JavaScript 中两个数组中的重复元素

标签 javascript ecmascript-6

<分区>

我有两个数组,我希望将这两个组合起来,重复的项目不亮,只添加新项目,我在控制台中看到组合的数组 我还想在控制台的列表中看到重复项 我的意思是,我需要两个输出,一个告诉我什么是重复项,另一个向我展示一个新的数组,该数组由两个没有重复项的数组组合而成。 我写了这段代码,但它不能正常工作 谢谢你指导我

预期输出:

newContact : [
  {
    "id": 1,
    "name": "Oliver"
  },
  {
    "id": 2,
    "name": "Liam"
  }
   {
    "id": 3,
    "name": "James"
  }
   {
    "id": 4,
    "name": "Lucas"
  }
]
duplicateContacts: Oliver

let array1 = [
  { id: 1, name: "Oliver" },
  { id: 2, name: "Liam" },
];
let array2 = [
  { id: 1, name: "Oliver" },
  { id: 3, name: "James" },
  { id: 4, name: "Lucas" },
];
let newContact = array1.filter((item) => item.id !== array2.id);
console.log("newContact :", newContact);
console.log("duplicateContacts:");

最佳答案

猜测重复意味着相同的id,将数组条目添加到映射中以查找重复项,并且映射包含唯一项

const array1 = [
  { id: 1, name: "Oliver" },
  { id: 2, name: "Liam" },
];
const array2 = [
  { id: 1, name: "Oliver" },
  { id: 3, name: "James" },
  { id: 4, name: "Lucas" },
];

const duplicates = [];
const map = new Map();

const fill = (array) => array.forEach(item => {
  if (map.has(item.id)) {
    duplicates.push(item);
  } else {
    map.set(item.id, item);
  }
});

fill(array1);
fill(array2);

console.log(duplicates);
console.log([...map.values()]);

编辑

要将数组作为输入,创建一个函数

const inspect = (...arrays) => {
    const duplicates = [];
    const map = new Map();

    const fill = (array) => array.forEach(item => {
      if (map.has(item.id)) {
        duplicates.push(item);
      } else {
        map.set(item.id, item);
      }
    });

    arrays.forEach(array => fill(array));

    console.log(duplicates);
    console.log([...map.values()]);
};


const array1 = [
  { id: 1, name: "Oliver" },
  { id: 2, name: "Liam" },
];
const array2 = [
  { id: 1, name: "Oliver" },
  { id: 3, name: "James" },
  { id: 4, name: "Lucas" },
];

inspect(array1, array2);

关于javascript - 检查 JavaScript 中两个数组中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70181982/

相关文章:

javascript - 静态变量 JavaScript ECMA6

javascript - 每次生产 Kafka 消息时都需要连接吗?

javascript - 如何在 SweetAlert 中而不是在对象上显示值

JavaScript 符号并没有阻止对象中的名称冲突

javascript - “箭头功能”和“功能”是否等效/可互换?

javascript - Redux 操作必须是普通对象

javascript - Node/Express : Adding middleware to router does not load

javascript - Javascript 验证中的正则表达式

javascript - 循环并比较 JavaScript 对象

javascript - SlickGrid 列类型