-
海绵宝宝撒
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)