Home > Software engineering >  How do I filter values in an object to display an array of values
How do I filter values in an object to display an array of values

Time:04-28

How do I fix my honorRoll function at the bottom so that it displays the names of all the students with GPA higher than the benchmark of 3.5?

Right now all I get back is an empty array, I would like to see [Bianca Pargas, Sameer Fares].

const GPA_BENCHMARK = 3.5;

let students = {
  1: {
    name: 'Egill Vignission',
    gpa: 3.4
  },
  2: {
    name: 'Bianca Pargas',
    gpa: 3.8
  },
  3: {
    name: 'Aisling O\'Sullivan',
    gpa: 3.4
  },
  4: {
    name: 'Sameer Fares',
    gpa: 3.9
  }
}

let honorRoll = Object.values(students).filter(student => {
  return students.gpa >= GPA_BENCHMARK;
});

console.log(honorRoll);

CodePudding user response:

in a very simple way you can do like that

const GPA_BENCHMARK = 3.5;

let students = {
  1: {
    name: 'Egill Vignission',
    gpa: 3.4,
  },
  2: {
    name: 'Bianca Pargas',
    gpa: 3.8,
  },
  3: {
    name: "Aisling O'Sullivan",
    gpa: 3.4,
  },
  4: {
    name: 'Sameer Fares',
    gpa: 3.9,
  },
};

let honorRoll = [];
for (let key in students) { 
  if (students[key].gpa >= GPA_BENCHMARK) {
    honorRoll.push(students[key]);
  }
}

console.log(honorRoll);
 

CodePudding user response:

You used students instead of student in your filter fn

  • Related