skip to Main Content

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


  1. 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.

    var input = {
      "2023-06": 7.2,
      "2023-08": 6.7,
      "2023-07": 5,
      "2022-04": 3.5,
      "2023-05": 6.1
    };
    var output = {};
    for (var key of Object.keys(input).sort().reverse())
      output[key] = input[key];
    console.log(output);
    Login or Signup to reply.
  2. A functional approach:

    const input = {
      "2023-06": 7.2,
      "2023-08": 6.7,
      "2023-07": 5,
      "2022-04": 3.5,
      "2023-05": 6.1
    };
    
    console.log(
      Object.keys(input).sort().reverse().reduce((r, key) => { r[key] = input[key]; return r}, {})
    );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search