Nemanja G
Nemanja G

Reputation: 1850

Find 2 highest values in an object - Javascript

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)?

Upvotes: 2

Views: 481

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386868

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);

Upvotes: 5

Related Questions