How to use Array.sort() with Object.entries() In Javascript

In this approach first, we convert the dictionary into an array of key-value pairs using Object.entries() then we sort that array based on the values, and then we convert it back into a dictionary using Object.fromEntries().

Example: The below example uses Array.sort() with Object.entries() methods to sort a Dictionary by Value in JavaScript.

JavaScript
const dict = { 'AI': 91, 'ML': 75, 'DSA': 88, 'IOT': 85 };
const sortedDict = Object.fromEntries(
      Object.entries(dict).sort(([,a],[,b]) => a- b)
);
console.log(sortedDict);

Output
{ ML: 75, IOT: 85, DSA: 88, AI: 91 }

How to Sort a Dictionary by Value in JavaScript ?

In JavaScript, dictionaries do not have a built-in method to sort them by their values. However, there are several approaches to achieve this functionality.

Below are the possible Approaches:

Table of Content

  • Using Array.sort() with Object.entries()
  • Using a custom sort function

Similar Reads

Using Array.sort() with Object.entries()

In this approach first, we convert the dictionary into an array of key-value pairs using Object.entries() then we sort that array based on the values, and then we convert it back into a dictionary using Object.fromEntries()....

Using a custom sort function

In this approach, we are defining a custom sort function that sorts the dictionary based on their corresponding values. The custom function uses Object.keys() to get an array of keys and then sort the array based on the values. Finally, we will construct the dictionary using Array.reduce()....

Contact Us