How to return object from an array with highest key values along with name - 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 }

Updated on: 01-Oct-2020

570 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements