Last active
November 30, 2023 10:36
-
-
Save ChathuraGH/86f51e59ffecff6ec09163546cb0659a to your computer and use it in GitHub Desktop.
Sort Js Dictionary to Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var dict = { | |
| "x": 1, | |
| "y": 6, | |
| "z": 9, | |
| "a": 5, | |
| "b": 7, | |
| "c": 11, | |
| "d": 17, | |
| "t": 3 | |
| }; | |
| // Create items array | |
| var items = Object.keys(dict).map(function(key) { | |
| return [key, dict[key]]; | |
| }); | |
| // Sort the array based on the second element | |
| items.sort(function(first, second) { | |
| return second[1] - first[1]; | |
| }); | |
| // Create a new array with only the first 5 items | |
| console.log(items.slice(0, 5)); | |
| // source | |
| // https://stackoverflow.com/questions/25500316/sort-a-dictionary-by-value-in-javascript | |
| // https://stackoverflow.com/a/25500462/13861187 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment