在集合A和集合B中,屬于集合A,同時也屬于集合B的元素組成的集合,就是交集。
在A中所有不屬于集合B元素,組合成集合,就是差集。
那么在平時的開發(fā)中,如何使用差集和交集來解決問題呢?
現(xiàn)在有這樣的場景,在一個表格編輯數(shù)據(jù)后,要把編輯前的數(shù)據(jù)和修改后的數(shù)據(jù),匯總。
源數(shù)據(jù)為:
const arr1 = [{ name: 11, id: 1 }, { name: 21, id: 2 }, { name: 31, id: 3 }, { name: 41, id: 4 }, { name: 51, id: 5 }, { name: 61, id: 6 }];
在頁面中表現(xiàn)為:
現(xiàn)在刪除第一行數(shù)據(jù),第二行的名字改為2109,第三行的名字改為3321;然后新增兩行,分別為:71、81。
數(shù)據(jù)如下:
const arr2 = [{ name: 2109, id: 2 }, { name: 3321, id: 3 }, { name: 41, id: 4 }, { name: 51, id: 5 }, { name: 61, id: 6 }, { name: 71, id: null }, { name: 81, id: null }];
頁面為:
由于是新增數(shù)據(jù)還沒有提交保存,所以對應的序號,也就是ID為空。
最終想要的效果圖下圖所示:
需要在表格中體現(xiàn)那些數(shù)據(jù)是修改、刪除、新增,哪些數(shù)據(jù)沒有改變。
思路:
- 源數(shù)據(jù)是一個數(shù)組arr1;
- 修改后的數(shù)據(jù)也是一個數(shù)組arr2;
- 刪除的數(shù)據(jù),在數(shù)組arr1中有,數(shù)組arr2中沒有;
- 修改的數(shù)據(jù),在數(shù)組arr1和arr2中,都找對應的ID;
- 新增的數(shù)據(jù),只出現(xiàn)在數(shù)組arr2中。
那么數(shù)組arr2與數(shù)組arr1的差集,就是新增的數(shù)據(jù):
let add = arr2.filter(x => arr1.every(y => y.id != x.id))
數(shù)組arr1與數(shù)組arr2的差集,就是刪除的數(shù)據(jù):
let del = arr1.filter(x => arr2.every(y => y.id != x.id))
修改或者沒有修改數(shù)據(jù),就是數(shù)組arr1和數(shù)組arr2的交集:
// arr1、arr2的交集
let arr12Inter = arr1.filter(x => arr2.some(y => x.id === y.id))
let arr21Inter = arr2.filter(x => arr1.some(y => x.id === y.id))
最后一步,就是組合所有的差集、交集,匯總成新的數(shù)組:
for (let index = 0; index < arr12Inter.length; index++) {
newArr.push({ oldData: arr21Inter[index], newData: arr12Inter[index] })
}
del.forEach(item => newArr.push({ oldData: item, newData: null }))
add.forEach(item => newArr.push({ oldData: null, newData: item }))
完整代碼:
const arr1 = [{ name: 11, id: 1 }, { name: 21, id: 2 }, { name: 31, id: 3 }, { name: 41, id: 4 }, { name: 51, id: 5 }, { name: 61, id: 6 }];
const arr2 = [{ name: 2109, id: 2 }, { name: 3321, id: 3 }, { name: 41, id: 4 }, { name: 51, id: 5 }, { name: 61, id: 6 }, { name: 71, id: null }, { name: 81, id: null }];
let newArr = [];
// arr1——>arr2的差集:刪除
let del = arr1.filter(x => arr2.every(y => y.id != x.id))
// arr2——>arr1的差集:新增
let add = arr2.filter(x => arr1.every(y => y.id != x.id))
// arr1、arr2的交集:修改
let arr12Inter = arr1.filter(x => arr2.some(y => x.id === y.id))
let arr21Inter = arr2.filter(x => arr1.some(y => x.id === y.id))
console.log("arr1與arr2的差集:", del)
console.log("arr2與arr1的差集:", add)
console.log("交集", arr12Inter, arr21Inter)
for (let index = 0; index < arr12Inter.length; index++) {
newArr.push({ oldData: arr21Inter[index], newData: arr12Inter[index] })
}
del.forEach(item => newArr.push({ oldData: item, newData: null }))
add.forEach(item => newArr.push({ oldData: null, newData: item }))
console.log("匯總:", newArr)
文章來源:http://www.zghlxwxcb.cn/news/detail-657817.html
使用交集、差集,僅僅是一種方式!文章來源地址http://www.zghlxwxcb.cn/news/detail-657817.html
到了這里,關(guān)于JavaScript:交集和差集的應用場景的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!