[英]compare two array of objects and get difference
嘲笑
a = [{id:123},{id:1234},{id:12345}]
b = [{id:123},{id:1234},{id:123456}]
代碼
a.filter((element)=> {
return b.some((ele) =>{
if (element.id === ele.id) {
return matched[element.id] = element.id
} else {
return unmatched[element.id] = element.id
}
});
});
預期 output
matched = {123: 123, 1234: 1234}
unmatched = {12345: 12345}
output
unmatched = {123: 123, 1234: 1234, 12345: 12345}
matched = {123: 123, 1234: 1234}
任何人都可以在這里幫助我。 我正在嘗試比較兩個 arrays 並將差異轉化為不同的對象
您可以將Set
或 object 用於a
並迭代b
以獲得正確的 object。
const a = [{ id: 123 }, { id: 1234 }, { id: 12345 }], b = [{ id: 123 }, { id: 1234 }, { id: 123456 }], aSet = new Set(a.map(({ id }) => id)), [matched, unmatched] = b.reduce((r, { id }) => { Object.assign(r[1 - aSet.has(id)], { [id]: id }); return r; }, [{}, {}]); console.log(matched); console.log(unmatched);
.as-console-wrapper { max-height: 100%;important: top; 0; }
直接使用對象的方法
const a = [{ _id: '123', index: 3 }, { _id: '1234', index: 3 }], b = [{ _id: '123', index: 2 }, { _id: '12345', index: 3 }], aSet = new Set(a.map(({ _id }) => _id)), [matched, unmatched] = b.reduce((r, o) => { r[1 - aSet.has(o._id)].push(o); return r; }, [[], []]); console.log(matched); console.log(unmatched);
.as-console-wrapper { max-height: 100%;important: top; 0; }
這會起作用:
a = [{id:123},{id:1234},{id:12345}];
b = [{id:123},{id:1234},{id:123456}];
function compare(a, b) {
const returnObj = { matched: [], unmatched: [] };
a.forEach(aItem => {
const found = b.find(bItem => JSON.stringify(aItem) === JSON.stringify(bItem));
returnObj[found ? 'matched' : 'unmatched'].push(aItem);
});
return returnObj;
}
const { matched, unmatched } = compare(a, b);
console.log(matched);
console.log(unmatched);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.