亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過新集合從對象中獲取唯一數組?

如何通過新集合從對象中獲取唯一數組?

慕田峪4524236 2023-07-14 16:32:28
如何通過新集合從對象中獲取唯一數組?我有一個包含對象的數組,如何獲得唯一的數組,但只能保留 id?IE:[{id: 1, title: 'test1'}, {id: 2, title: 'test2'}]const arr = [{id: 1, title: 'test1'}, {id: 2, title: 'test2'}, {id: 1: title: 'test1'}]const filtered = arr.filter((item) => item.title)const result = Array.from(new set(arr))
查看完整描述

2 回答

?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

您可以使用哈希表并獲取它的值。


這種方法采用最后找到的具有相同id.


const

    array = [{ id: 1, title: 'first' }, { id: 2, title: 'test2' }, { id: 1, title: 'last' }],

    unique = Object.values(array.reduce((r, o) => (r[o.id] = o, r), {}));


console.log(unique);


通過使用Set帶有閉包的 a ,您可以過濾數組。


這種方法采用第一個找到的具有相同id.


const

    array = [{ id: 1, title: 'first' }, { id: 2, title: 'test2' }, { id: 1, title: 'last' }],

    unique = array.filter((s => ({ id }) => !s.has(id) && s.add(id))(new Set));


console.log(unique);


查看完整回答
反對 回復 2023-07-14
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

比起集合,Map 可能更好,只需創建一個以 id 為鍵的映射即可。


例如。


const arr = [{id: 1, title: 'test1'}, {id: 2, title: 'test2'}, {id: 1, title: 'test1'}];


const d = new Map(arr.map(m => [m.id, m]));


console.log([...d.values()]);


查看完整回答
反對 回復 2023-07-14
  • 2 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號