How to use Object.keys() and Array.sort() In Typescript
This approach involves first converting the dictionary into an array of key-value pairs using Object.entries(). We then sort these pairs based on their corresponding values using Array.sort(). Finally, we reconstruct the sorted dictionary from the sorted array.
Example:
function sortDictByValue(dict: Record<string, number>): Record<string, number> {
const entries = Object.entries(dict);
const sortedEntries = entries.sort((a, b) => b[1] - a[1]);
const sortedDict: Record<string, number> = {};
sortedEntries.forEach(([key, value]) => {
sortedDict[key] = value;
});
return sortedDict;
}
const dict: Record<string, number> = {
'Hyundai': 105,
'Tata': 120,
'Mahindra': 98,
'Renault': 113
};
const sortedDict: Record<string, number> = sortDictByValue(dict);
console.log(sortedDict);
Output
{ Tata: 120, Renault: 113, Hyundai: 105, Mahindra: 98 }
How to Sort a Dictionary by Value in TypeScript ?
In TypeScript, dictionaries are objects that store key-value pairs. Sorting a dictionary by value involves arranging the key-value pairs based on the values in ascending or descending order.
The below approaches can be used to accomplish this task:
Table of Content
- Using Object.entries() and Array.sort() method
- Using a custom sorting function
- Using Object.keys() and Array.sort()
Contact Us