user12559575
user12559575

Reputation: 9

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 } 

Upvotes: 0

Views: 86

Answers (4)

Brett DeWoody
Brett DeWoody

Reputation: 62743

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

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

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

Upvotes: 0

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

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%}

Upvotes: 0

Cristopher Rosales
Cristopher Rosales

Reputation: 476

Use

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

Upvotes: 3

Related Questions