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

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

獲取對象數組中每個唯一鍵的最大值 (Javascript)

獲取對象數組中每個唯一鍵的最大值 (Javascript)

慕容708150 2022-08-04 16:00:14
我有一個對象數組,如下所示:const data = [    { depth: 0, length: 5 },    { depth: 1, length: 8 },    { depth: 1, length: 11 },    { depth: 1, length: 6 },    { depth: 1, length: 8 },    { depth: 1, length: 11 },    { depth: 1, length: 6 },    { depth: 1, length: 8 },    { depth: 2, length: 16 },    { depth: 2, length: 25 }];我需要獲取每個鍵的最高值。我想要的數組是:lengthdepthconst result = [    { depth: 0, length: 5 },    { depth: 1, length: 11 },    { depth: 2, length: 25 }];數組可以是 X 深度。我見過的其他示例僅獲得最大值,或具有最大值的單個對象,而我需要每個鍵的最大值。data
查看完整描述

1 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

使用 as 鍵將數組縮小為 Map。如果當前對象在 Map 中不存在,或者當前對象是 Map 小于當前項目的 ,則存儲該項目。通過展開 Map 的值迭代器轉換為數組:depthlengthlengthdepth


const data = [{"depth":0,"length":5},{"depth":1,"length":8},{"depth":1,"length":11},{"depth":1,"length":6},{"depth":1,"length":8},{"depth":1,"length":11},{"depth":1,"length":6},{"depth":1,"length":8},{"depth":2,"length":16},{"depth":2,"length":25}];


const result = [...data.reduce((r, o) =>

  (!r.has(o.depth) || r.get(o.depth).length < o.length) ? r.set(o.depth, o) : r

, new Map()).values()];


console.log(result);


查看完整回答
反對 回復 2022-08-04
  • 1 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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