![]() |
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 Examples of Sorting a Dictionary by Value in TypeScriptUsing Object.entries() and Array.sort() methodIn 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.
Output{ manohar: 19, Prasad: 21, Saurabh: 23 } Using a custom sorting functionIn this approach, we define a custom sorting function that sorts the dictionary’s key-value pairs based on their values. This function uses Object.keys() to extract an array of keys and sorts it according to the corresponding values. Finally, we reconstruct the dictionary using Array.reduce(). Example: This example utilizes the Custom Sorting Function to sort a Dictionary by its Values in TypeScript.
Output{ Tata: 120, Renault: 113, Hyundai: 105, Mahindra: 98 } Using Object.keys() and Array.sort()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:
Output{ Tata: 120, Renault: 113, Hyundai: 105, Mahindra: 98 } |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |