背景
日常开发过程中,我们经常会碰到需要对一些数据进行处理的情况,索性就整理个文档吧,方便日后查阅。
javascript 中数组对象求交集、并集、补集
如下代码:
const a = [
{
'categoryId': 1,
'categoryIdLevelOne': 750611334,
'categoryIdLevelThree': 750611336,
'categoryIdLevelTwo': 750611335,
'id': 2697,
'level': 3,
'shopId': 12430,
'skipLayoutFlag': false,
'status': 1
},
{
'categoryId': 2,
'categoryIdLevelOne': 750611472,
'categoryIdLevelTwo': 750611473,
'id': 2701,
'level': 2,
'shopId': 12430,
'skipLayoutFlag': false,
'status': 2
},
{
'categoryId': 3,
'categoryIdLevelOne': 750611487,
'categoryIdLevelTwo': 750611488,
'id': 2702,
'level': 2,
'shopId': 12430,
'skipLayoutFlag': false,
'status': 1
}
]
const b = [
{
'categoryId': 2,
'categoryIdLevelOne': 750611334,
'categoryIdLevelThree': 750611336,
'categoryIdLevelTwo': 750611335,
'id': 2697,
'level': 3,
'shopId': 12430,
'skipLayoutFlag': false,
'status': 1
},
{
'categoryId': 3,
'categoryIdLevelOne': 750611472,
'categoryIdLevelTwo': 750611473,
'id': 2701,
'level': 2,
'shopId': 12430,
'skipLayoutFlag': false,
'status': 2
},
{
'categoryId': 4,
'categoryIdLevelOne': 750611487,
'categoryIdLevelTwo': 750611488,
'id': 2702,
'level': 2,
'shopId': 12430,
'skipLayoutFlag': false,
'status': 1
}
]
复制代码
- 交集
const c = a.filter( a => b.some(b => b.categoryId === a.categoryId))
复制代码
- 补集(差集)
const d = a.filter(x => b.every(y => y.categoryId !== x.categoryId))
复制代码
- 并集
const e = b.filter(y => a.every(x => x.categoryId !== y.categoryId)).concat(a)
复制代码