js數據處理總結

背景

平常開發過程當中,咱們常常會碰到須要對一些數據進行處理的狀況,索性就整理個文檔吧,方便往後查閱。javascript

javascript 中數組對象求交集、並集、補集

以下代碼:java

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)
複製代碼
相關文章
相關標籤/搜索