
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Return Object from Array with Highest Key Values in JavaScript
Suppose, we have an array of objects that contains information about marks of some students in a test −
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 } ];
We are required to write a JavaScript function that takes in one such array and returns a object with the name and total of the student that have highest value for total.
Therefore, for the above array, the output should be −
{ name: 'Stephen', total: 85 }?
Example
Following is the code −
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));
Output
This will produce the following output on console −
{ name: 'Stephen', total: 85 }
Advertisements