对象数组根据某个属性去重
方法一:
function unique(arr, key) {
const res = new Map();
return arr.filter((a) => !res.has(a[key]) && res.set(a[key], 1))
}
方法二:
function unique(arr, key) {
let hash = {};
const newArr = arr.reduce((preVal, curVal) => {
hash[curVal[key]] ? '' : hash[curVal[key]] = true && preVal.push(curVal);
return preVal
}, [])
return newArr
}
对象数组根据多个属性去重
function unique(arr, keys) {
const dict = {};
return arr.filter(t => {
const tKeys = keys.map(item => {
return t[item]
})
const key = tKeys.join('|')
if (dict[key]) {
return false
}
dict[key] = true
return true
})
}