I have a json like this:
{ "2023-06":7.2, "2023-08":6.7, "2023-07":5, "2022-04":3.5, "2023-05":6.1 }
How can I sort it to get it in chronological order? Starting with latest date and ending with the most far in history?
I am able to sort by values, but not by keys. I have tried sth like this: https://stackoverflow.com/questions/3859239/sort-json-by-date
With different variations, but didnt suceed.
I am expecting:
{ "2023-08":6.7, "2023-07":5, "2023-06":7.2, "2023-05":6.1, "2022-04":3.5 }
2
Answers
Conceptually, there is no order defined on the members of a Javascript object. But if you loop over the object keys in sorted order and add the members to a new object
output
, which is initially empty, in the same order, the new object will show its members in the desired order when you log it.A functional approach: