ES6 通過 set 和 map 實現對象數組去重


1.方法一:

// ES6對象數組所有屬性去重,篩選每個數組項的字符
function unique(arr) {
  const map = new Map()
  return arr.filter( item => !map.has(JSON.stringify(item)) && map.set(JSON.stringify(item), 1))
}

// 或

function unique(arr) {
  return [...new Set(arr.map(e => JSON.stringify(e)))].map(e => JSON.parse(e))
}

2.方法二:

// ES6根據一維對象數組某個屬性去重且該屬性的值為簡單數據類型,比較實用的一種的方法,也基本沒有什么性能影響
function unique(arr, key) {
  const map = new Map()
  return arr.filter((item) => !map.has(item[key] + '') && map.set(item[key] + '', 1))
}

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM