Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the three key/value pairs with the lowest value from an object?

I have an object as below:

var countryobj = {
    "Canada": 10,
    "Peru": 1,
    "Argentina": 5,
    "Colombia": 2,
    "Mexico": 8
};

I want to get the first 3 smallest key value pair so that my output would be:

Peru: 1
Colombia: 2
Argentina: 5

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just get the Object.entries and sort them based on their value in ascending order, then print the first three items formatted how you like.

var countryobj = {
 "Canada": 10,
 "Peru": 1,
 "Argentina": 5,
 "Colombia": 2,
 "Mexico": 8
};

const entries = Object.entries(countryobj).sort(([, a], [, b]) => a - b);

for (let i = 0; i < 3; i++) {
  console.log(entries[i][0] + ": " + entries[i][1]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading