js数组普通去重、根据数组中某个对象值去重

1、 普通去重

function unique1 (arr) {
  return Array.from(new Set(arr))
}


function unique2 (arr) {
    return arr.filter((item, index)=> {
        return arr.indexOf(item) === index
    })
}

unique([1,2,3,3,4,4,4,5])
// [1, 2, 3, 4, 5]

2、根据数组中某个对象值去重

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


unique([
  {
  from:'张三',
  to: '河南'
  },
  {
    from:'王二',
    to: '杭州'
  },
  {
    from:'王二',
    to: '河南'
  },
  {
    from:'王二',
    to: '山东'
  },
],'from')

 

你可能感兴趣的:(JavaScript)