ElMuchacho
ElMuchacho

Reputation: 300

Trying to loop over the object and find the key with max value - getting inaccurate answer

Trying to find max value in values but keep getting inaccurate value. What have I done wrong?

  const findBestEmployee = function(employees) {
  let theBest = Object.values(employees)[0];
  for (let [key, value] of Object.entries(employees)) {
    if (value > theBest){
      theBest = value
    }
    return key
}
};



console.log(
  findBestEmployee({
    ann: 29,
    david: 35,
    helen: 1,
    lorence: 99,
  })
);

Output is ann istead of lorence - what i did wrong?

Upvotes: 1

Views: 311

Answers (3)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

There's another way around, based on Array.prototype.reduce():

const employees = {ann:29,david:35,helen:1,lorence:99},

      getKeyOfMax = obj => 
        Object
          .keys(obj)
          .reduce((r,key) => 
            obj[key]>obj[r] ? key : r)
            
console.log(getKeyOfMax(employees))
.as-console-wrapper{min-height:100%;}

Upvotes: 1

muasif80
muasif80

Reputation: 6006

You have to maintain the key too and then return the best key after the loop. You are returning it on the first run of the loop by putting it inside the loop.

const findBestEmployee = function(employees) {
  let theBest = Object.values(employees)[0];
  let theBestKey = Object.keys(employees)[0];
  for (let [key, value] of Object.entries(employees)) {
    if (value > theBest){
      theBest = value;
      theBestkey = key;
    }

  }
  return theBestkey;
};

Upvotes: 1

Claudio Busatto
Claudio Busatto

Reputation: 761

You are returning the value inside the for loop, therefore the first item is always returned as the bestEmployee.

const findBestEmployee = function(employees) {
  let bestPerformance = Object.values(employees)[0];
  let bestEmployeeName = Object.values(employees)[1];
  for (let [name, performance] of Object.entries(employees)) {
    if (performance > bestPerformance) {
      bestPerformance = performance;
      bestEmployeeName = name;
    }
  }
  return bestEmployeeName;
};

console.log(
  findBestEmployee({
    ann: 29,
    david: 35,
    helen: 1,
    lorence: 99,
  }),
);
// lorence

Upvotes: 1

Related Questions