如何使用最高鍵值和名稱從陣列中返回物件——JavaScript?
假設我們有一個物件陣列,其中包含一些學生在測試中的成績資訊 −
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: 82 }, { name: 'Cameron', total: 30 }, { name: 'Geoff', total: 30 } ];
我們需要編寫一個 JavaScript 函式,它接收這樣的一個數組並返回一個物件,其中包含總分最高學生的姓名和總分。
因此,對於上面的陣列,輸出應為 −
{ 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: 82 }, { name: 'Cameron', total: 30 }, { name: 'Geoff', total: 30 } ]; const pickHighest = arr => { const res = { name: '', total: -Infinity }; arr.forEach(el => { const { name, total } = el; if(total > res.total){ res.name = name; res.total = total; }; }); return res; }; console.log(pickHighest(students));
輸出
這將在控制檯中生成以下輸出 −
{ name: 'Stephen', total: 85 }
廣告