js根據數組中對象的某個屬性值進行去重

var arr = [
  {
  from:'張三',
  to: '河南'
  },
  {
    from:'王二',
    to: '阿里'
  },
  {
    from:'王二',
    to: '杭州'
  },
  {
    from:'王二',
    to: '山東'
  },
]
有如上數組,想根據數組中的對象的from屬性進行去重,如果from一樣的話,重複只保留一條。根據ES6屬性編寫函數代碼如下:

function unique(arr1) {
  const res = new Map();
  return arr1.filter((a) => !res.has(a.from) && res.set(a.from, 1))
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章