1

I'm faced with a problem I haven't seen before. I don't need the lowest value but I need the variable that has the lowest value.

I have 5 variables, let's say they are set up like so (which they obviously are not):

rat_professionalism_pct = 57.1
rat_responsiveness_pct = 58.6
rat_expertise_pct = 61.0
rat_courtesy_pct = 44.4
rat_teamplayer_pct = 50.9

My goal is to have a sentence like:

Your highest rated attribute is 'expertise'.

My standard way of doing this is:

let rat_attribute;
let rat_pct;
let rat_attribute_highest = 'professionalism';
let rat_pct_highest = per_rat_professionalism_pct;

for (let b = 1; b <= 5; b++) {

  switch (b) {
    case 1: rat_attribute = 'professionalism'; rat_pct = per_rat_professionalism_pct; break;
    case 2: rat_attribute = 'responsiveness'; rat_pct = per_rat_responsiveness_pct; break;
    case 3: rat_attribute = 'expertise'; rat_pct = per_rat_expertise_pct; break;
    case 4: rat_attribute = 'courtesy'; rat_pct = per_rat_courtesy_pct; break;
    case 5: rat_attribute = 'professionalism'; rat_pct = per_rat_professionalism_pct; break;
  }
                        
  if (rat_pct > rat_pct_highest) {

    rat_attribute_highest = rat_attribute; rat_pct_highest = rat_pct;

  }

}

This is a language-independent method that should work in any programming language since it just uses the base pattern of conditionals and loops.

However, I recognize that I am new to Javascript and don't (by default) jump to some of the coolest functions that are native to JS, like the array functions.

Is there a better way to do this, for example, using .reduce()?

Nick
  • 466
  • 1
  • 6
  • 12

2 Answers2

1

Why not just put all the variables as keys in an object and then find the maximum value and also the key associated with that maximum value

const obj = {
  professionalism: 57.1,
  responsiveness: 58.6,
  expertise: 61.0,
  courtesy: 44.4,
  teamplayer: 50.9
}

const maxValue = Math.max(...Object.values(obj));

for (const k of Object.keys(obj)) {
  if (obj[k] == maxValue) {
    console.log(`Your highest rated attribute is '${k}'`);
    break;
  }
}

Here's another way you could achieve the desired result

const obj = {
  professionalism: 57.1,
  responsiveness: 58.6,
  expertise: 61.0,
  courtesy: 44.4,
  teamplayer: 50.9
}

let key = '', value = -1;

for (const [k, v] of Object.entries(obj)) {
  if (v > value) {
    key =  k;
    value = v;
  }
}

console.log(`Your highest rated attribute is '${key}'`);
Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

For a one liner, taken from: Getting key with the highest value from object

const obj = {  
    professionalism: 57.1,
    responsiveness: 58.6,
    expertise: 61.0,
    courtesy: 44.4,
    teamplayer: 50.9
};

const maxKey = Object.keys(obj).reduce((a, b) => obj[a] > obj[b] ? a : b);
console.log(`Your highest rated attribute is '${maxKey}'`);

If some variables are equal it will retain the first one encountered

SGali
  • 70
  • 1
  • 1
  • 6