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.
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
Contact Us