2

I am trying to get the top 2 highest values from an object:

emotions = {
      joy: 52,
      surprise: 22,
      contempt: 0,
      sadness: 98,
      fear: 60,
      disgust: 20,
      anger: 1,
  };

I understand I can do Math.max() with all these values, but it will return just the value of sadness in this example. Can I somehow get top 2, with label (sadness) and value (98)?

Nemanja G
  • 1,760
  • 6
  • 29
  • 48
  • Just sort them and take the first 2 elements? – Robin Zigmond Oct 19 '18 at 09:29
  • 2
    https://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value see this for hint – Ankit Agarwal Oct 19 '18 at 09:29
  • What is your required output format? `[{sadness:98},{fear:60}]` or `[{fear:60},{sadness:98}]` or `{fear:60, sadness:98}` (in the last case it will be in no particular order, of course) – Jaromanda X Oct 19 '18 at 09:38
  • @JaromandaX It would be ideal to get both label and value, since I need to write out as text, 1st one then 2nd one – Nemanja G Oct 19 '18 at 09:41
  • right ... but **what actual format do you want the actual output to be** all three I suggested have label and value - perhaps `[["fear", 60],["sadness", 98]]` or `[["sadness", 98],["fear", 60]]` - these also have both label and value – Jaromanda X Oct 19 '18 at 09:42
  • @JaromandaX the first one would work [{sadness:98},{fear:60}] – Nemanja G Oct 19 '18 at 09:44
  • They all work, it depends on what you want :p – Jaromanda X Oct 19 '18 at 09:44

1 Answers1

5

You could get the entries, sort them and return objects which are converted to a single one.

var emotions = { joy: 52, surprise: 22, contempt: 0, sadness: 98, fear: 60, disgust: 20, anger: 1 },
    top2 = Object
        .entries(emotions)
        .sort(({ 1: a }, { 1: b }) => b - a)
        .slice(0, 2)
        .map(([label, value]) => ({ label, value }));
  
 console.log(top2);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392