-3

this is my first question here so I'll try to be precise as much as possible.

I have homework which requires me to create an array of 5 objects which are students with their name, surname and average grade.

The average grade being set as any number from 2 to 5 for example: 2.50, 3.34, 4.95 etc. My only job here is to print out into the console the name and surname of the student with the lowest average grade.

For the life of me I couldn't figure out how to do it and googling didn't help or at least I didn't know how to look for it.

I could only define the objects but I don't know how to list through the objects and find the lowest 'avgGrade'.

var students = [
  { name: "John", surname: "Doe", avgGrade: 5.0 },
  { name: "Mike", surname: "Adams", avgGrade: 4.2 },
  { name: "Mark", surname: "Davis", avgGrade: 2.1 },
  { name: "Jane", surname: "Jones", avgGrade: 3.99 },
  { name: "Sarah", surname: "Quinn", avgGrade: 2.8 },
];
lejlun
  • 4,140
  • 2
  • 15
  • 31
Milan
  • 3
  • 1
  • 2
    It's an array of objects. So you can step through it with a for-loop or you can use the array's `forEach` method. – enhzflep Aug 14 '21 at 21:40
  • [Compare JavaScript Array of Objects to Get Min / Max](https://stackoverflow.com/questions/8864430/compare-javascript-array-of-objects-to-get-min-max) – 3limin4t0r Aug 14 '21 at 21:52
  • Check out `for...of`, where you can loop through an array in a simple way: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in – Rickard Elimää Aug 14 '21 at 21:57

1 Answers1

-2

You can do this using a for...of loop,

We can declare two variables lowestAvg, which keeps track of the lowest average grade we have seen so far. And lowestStudent, which keeps track of the student that owns that grade.

We go through each student using a for...of loop checking their grade against the lowest that we've seen so far.

Full code:

let students = [ { name: "John", surname: "Doe", avgGrade: 5.0 }, { name: "Mike", surname: "Adams", avgGrade: 4.2 }, { name: "Mark", surname: "Davis", avgGrade: 2.1 }, { name: "Jane", surname: "Jones", avgGrade: 3.99 }, { name: "Sarah", surname: "Quinn", avgGrade: 2.8 }, ];

let lowestAvg = 10;
let lowestStudent = null;

for (let student of students) {
  if (student.avgGrade <= lowestAvg) {
    lowestStudent = student;
    lowestAvg = student.avgGrade;
  } 
}

console.log(lowestStudent);
console.log(lowestStudent.name, lowestStudent.surname);
lejlun
  • 4,140
  • 2
  • 15
  • 31