简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM