简体   繁体   中英

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

As I'm trying to get an object with all the names with the highest values, I am only getting one value and name rather than all existing names with the same highest value? // { name: 'Stephen', total: 85 } Any help would be appreciated.

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)

Another solution using a single forEach loop, which returns an array of the top students.

 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));

You could take a single loop with reduce by returning the object with the greatest total .

 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);

One pass over the array is absolutely enough to do the job with 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%}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM