4 回答
TA贡献1809条经验 获得超8个赞
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);
TA贡献1946条经验 获得超3个赞
有点乱,但它有效。首先查找仅出现一次的 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);
TA贡献2016条经验 获得超9个赞
好吧,所以也许不是。以下是一种像您要求的那样检索输出的方法:
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]));
TA贡献1796条经验 获得超4个赞
只是另一种方法:
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)
添加回答
举报