How to use a custom sort function In Javascript
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().
Example: The below example uses the Custom Sort Function to sort a Dictionary by Value in JavaScript.
function sortDictByValue(dict) {
return Object.keys(dict)
.sort((a, b) => dict[b] - dict[a])
.reduce((acc, key) => {
acc[key] = dict[key];
return acc;
}, {});
}
const dict =
{ 'banana': 5, 'apple': 10, 'orange': 8, 'grape': 3 };
const sortedDict = sortDictByValue(dict);
console.log(sortedDict);
Output
{ apple: 10, orange: 8, banana: 5, grape: 3 }
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