簡體   English   中英

如何從具有最高鍵值和名稱的數組中返回對象?

[英]how to return object from array with highest key values along with name?

當我試圖獲得一個具有最高值的所有名稱的對象時,我只獲得了一個值和名稱,而不是所有具有相同最高值的現有名稱? // { name: 'Stephen', total: 85 } 任何幫助將不勝感激。

const students = [
{ name: 'Andy', total: 40 },
{ name: 'Seric', total: 50 },
{ name: 'Stephen', total: 85 },
{ name: 'David', total: 30 },
{ name: 'Phil', total: 40 },
{ name: 'Eric', total: 85 },
{ name: 'Cameron', total: 30 },
{ name: 'Geoff', total: 30 }];

const max = Math.max(...students.map(e => e.total))

const result = students.find(student => student.total === max)

console.log(result)//{ name: 'Stephen', total: 85 } 

const result = students.filter(student => student.total == max)

另一種使用單個forEach循環的解決方案,它返回一個由頂尖學生組成的數組。

 const students = [{ name: 'Andy', total: 40 },{ name: 'Seric', total: 50 },{ name: 'Stephen', total: 85 },{ name: 'David', total: 30 },{ name: 'Phil', total: 40 },{ name: 'Eric', total: 85 },{ name: 'Cameron', total: 30 },{ name: 'Geoff', total: 30 }]; const findTop = (students) => { let max = 0; let top = []; students.forEach(student => { if (student.total > max) { max = student.total; top = [student]; } else if (student.total === max) { top.push(student); } }) return top; }; console.log(findTop(students));

您可以通過返回具有最大total的對象來使用 reduce 進行單個循環。

 const students = [{ name: 'Andy', total: 40 }, { name: 'Seric', total: 50 }, { name: 'Stephen', total: 85 }, { name: 'David', total: 30 }, { name: 'Phil', total: 40 }, { name: 'Eric', total: 85 }, { name: 'Cameron', total: 30 }, { name: 'Geoff', total: 30 }] highest = students.reduce((r, o) => { if (!r || r[0].total < o.total) return [o]; if (r[0].total === o.total) r.push(o); return r; }, undefined); console.log(highest);

一次遍歷數組絕對足以使用Array.prototype.reduce()完成這項工作:

 const students=[{name:'Andy',total:40},{name:'Seric',total:50},{name:'Stephen',total:85},{name:'David',total:30},{name:'Phil',total:40},{name:'Eric',total:85},{name:'Cameron',total:30},{name:'Geoff',total:30}], result = students.reduce((res,student,idx) => ( !idx || student.total > res[0]['total'] ? res = [student] : student.total == res[0]['total'] ? res.push(student) : true , res),[]) console.log(result)
 .as-console-wrapper {min-height:100%}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM