javascript 去除重複的物件

const arr = [
  {name:'jackie', value:10},
  {name:'jackie', value:20},
  {name:'jackie', value:20},
  {name:'tom', value:30},
];

const result = [...new Set(arr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));

console.log(result); 

// [{name: "jackie", value: 10}, {name: "jackie", value: 20}, {name: "tom", value: 30}]

第一步先使用new Set並透過mapJSON.stringify把每一個陣列內的物件轉為字串,
再透過展開運算符[...]來把剛才Set的結果轉為陣列,
最後再用一次map把裡面的物件字串透過JSON.parse再轉回物件。

[…new Set(arr)] 可以刪除重複的元素

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = [...new Set(ages)]

console.log(uniqueAges) // [26,27,28,29,30]

而.map()又是怎作用的呢?

let A = [9000, 8500, 5500, 6500];
let B = A.map(item => item*2);

console.log(B) // [18000, 17000, 11000, 13000]

相關資料來源:

https://ithelp.ithome.com.tw/articles/10215281

https://guahsu.io/2018/04/JavaScript-Duplicates-Array-Object/

Please follow and like us:
Pin Share

發表迴響