天天看點

#yyds幹貨盤點#JS對象數組去重

對象數組去重(重複鍵)

arrDistinctByKey(arr, key){
  const temp = new Map(); // 使用Map可以比對多種類型,不限于字元串
  return arr.filter((item) => !temp.has(item[key]) && temp.set(item[key], true));
}

// 常用于過濾清單
const list = [{id: 1, name: 'xiaoming'}, {id: 1, name: 'xiaoming'}, {id: 2, name: 'xiaoliang'}];
const newArr = arrDistinctByKey(list, 'id');
// newArr: [{id: 1, name: 'xiaoming'}, {id: 2, name: 'xiaoliang'}]      

5. 對象數組取交集(相同鍵)

``` js
arrIntersectionByKey(arr1, arr2, key) {
  const arr2Keys = arr2.map(item => item[key]);
  return arr1.filter(item => arr2Keys.includes(item[key]));
}

// 例如找出使用者已領券中包含的本次即将發放的立減券,彈窗告知使用者已領取其中的某些券
const receivedCoupons = [{ name: '立減券' },{ name: '折扣券' }]; // 已領的券
const welfareCoupons = [{ stockId: '立減券' }]; // 本次要發放的福利券
// 使用者已領取的福利券,不再重複發放
arrIntersectionByKey(receivedCoupons,welfareCoupons, 'name');
// [{ name: '立減券' }]