This write-up will state the method for sorting a dictionary by values in JavaScript.
How to Sort a Dictionary by Value in JavaScript?
To sort a dictionary by value in JavaScript, add data in the dictionary by using the “entries()” method and then sort the entries with the help of the “sort()” JavaScript method. For practical implications, check out the stated examples.
Example 1: Sorting the Dictionary Based on Numeric Values
To sort the dictionary element, first of all, add the element in a string and store it in the initialized variable:
x: 102,
y: 101,
y: 103,
};
Invoke the “entries()” for returning an updated array iterator object that contains the key/value pairs for the individual index in the array:
Now, the “sort()” method is used along a compared call back function for sorting:
Lastly, call the “log()” method and pass the “JSON.stringify()”. This method converts a JavaScript value to a JSON string:
Output
It can be seen that the dictionary elements are sorted by values:
Example 2: Sorting the Dictionary Based on String Values
You can also sort the dictionary element according to the string values or alphabetically. In this particular example, insert the object values as a string along with the values and store it as follows:
"Jenny": 34, "Jack": 08, "Hafsi": 07, "Mari": 92,
"Sarah": 17, "Jacob": 81, "Marry": 98
};
Call the “object.keys()” method to collect the keys of the dictionary and then map the keys using the “map()” method:
Now, sort the elements with the help of the sort() method:
(first, second) => { return first[1] - second[1] }
);
Next, use the map() method along the call back function and store the mapped element in a variable:
Lastly, utilize the “log()” method and pass the argument “keys” to display the output on the console:
Output
That’s all about sorting the dictionary by value in JavaScript with different examples.
Conclusion
To sort a dictionary by values in JavaScript, first, collect the keys of a dictionary using the “object.keys()” and map the keys with the help of the “map()” method. After that, sort the dictionary elements by values using the sort() method with a compared call-back function. This tutorial has stated the method for sorting the dictionary elements by value in JavaScript.