对象数组根据某个或多个属性去重

908 阅读1分钟

对象数组根据某个属性去重

方法一:

function unique(arr, key) {
  const res = new Map();
  return arr.filter((a) => !res.has(a[key]) && res.set(a[key], 1))
}

image.png

方法二:

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
}

image.png

对象数组根据多个属性去重

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
  })
}

image.png