抓取数组中没有任何重复项的对象的最有效方法

我有2个脚本对象数组:

arr1=[{'id':'A'},{'id':'B'}, {'id':'C'}];
arr2=[{'id':'A'},{'id':'C'}, {'id':'D'}, {'id': 'E'}];

如何仅获取没有重复项的元素?

谢谢。

编辑

我不想删除重复项。我只想获取唯一对象。

output = [{'id':'B'}, {'id':'D'}, {'id':'E'}]

output = [{'id':'A'},{'id':'B'}, {'id':'C'}, {'id':'D'}, {'id':'E'}]

抱歉,如果我不清楚


凤凰求蛊
浏览 103回答 4
4回答

海绵宝宝撒

arr1=[{'id':'A'},{'id':'B'}, {'id':'C'}];arr2=[{'id':'A'},{'id':'C'}, {'id':'D'}, {'id': 'E'}];const out = Object.entries(arr1.concat(arr2).reduce((a, c) => {  a[c.id] = a[c.id] || 0;  a[c.id]++;  return a;}, {})).filter(([k, v]) => v === 1).map(([k]) => ({id: k}));console.log(out);

智慧大石

有点乱,但它有效。首先查找仅出现一次的 id,然后筛选组合数组以仅包含唯一 ID。arr1 = [{ id: "A" }, { id: "B" }, { id: "C" }];arr2 = [{ id: "A" }, { id: "C" }, { id: "D" }, { id: "E" }];function getCount(array, elem) {    return array.filter((e) => e === elem).length;}uniqueIds = [...arr1, ...arr2]    .map((e) => e.id)    .filter((e, i, a) => getCount(a, e) === 1);let uniques = [...arr1, ...arr2].filter((e) => uniqueIds.includes(e.id));console.log(uniques);

慕沐林林

好吧,所以也许不是。以下是一种像您要求的那样检索输出的方法:arr1=[{'id':'A'},{'id':'B'}, {'id':'C'}];arr2=[{'id':'A'},{'id':'C'}, {'id':'D'}, {'id': 'E'}];function getUniques(arr) {  let counter = arr.reduce((acc, val) =>    (acc[val.id] = (acc[val.id] || 0) + 1, acc), {});  return Object.keys(counter)    .filter(k => counter[k] === 1)    .map(k => ({id: k}));}console.log(getUniques([...arr1, ...arr2]));

SMILET

只是另一种方法: arr1=[{'id':'A'},{'id':'B'}, {'id':'C'}]; arr2=[{'id':'A'},{'id':'C'}, {'id':'D'}, {'id': 'E'}]; var res = []; var newArr = arr1.concat(arr2); var reverseArr = newArr.slice().reverse(); newArr.forEach((el,idx)=> { let iex = newArr.findIndex((e,i)=> e.id == el.id ); if (iex === idx && iex === newArr.length - (reverseArr.findIndex((e,i)=> e.id ==    el.id )+ 1) ){     res.push(el)   }});console.log(res) 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript