How to use Object.entries() and Array.sort() method In Typescript
In this approach, we begin by converting the dictionary into an array of key-value pairs using Object.entries(). Then, we sort this array based on the values. Finally, we convert the sorted array back into a dictionary using Object.fromEntries().
Example: This example utilizes Array.sort() and Object.entries() methods to sort a Dictionary by its Values in TypeScript.
const dict: Record<string, number> =
{
'Prasad': 21,
'Saurabh': 23,
'manohar': 19
};
const sortedDict1: Record<string, number> = Object.fromEntries(
Object.entries(dict).sort((a, b) => a[1] - b[1])
);
console.log(sortedDict1);
Output
{ manohar: 19, Prasad: 21, Saurabh: 23 }
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()