0

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 Answers2

0

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);
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31
0

You could sort the keys and construct a new object in a reversed order:

const input = {
  "2023-06": 7.2,
  "2023-08": 6.7,
  "2023-07": 5,
  "2022-04": 3.5,
  "2023-05": 6.1
};

const keys = Object.keys(input).sort(), result = {};
let i = keys.length;
while(i--) result[keys[i]] = input[keys[i]];

console.log(result);

enter image description here

<script benchmark data-count="1000000">
const input = {
  "2023-06": 7.2,
  "2023-08": 6.7,
  "2023-07": 5,
  "2022-04": 3.5,
  "2023-05": 6.1
};

// @benchmark Heiko
var output = {};
for (var key of Object.keys(input).sort().reverse())
  output[key] = input[key];
output;

// @benchmark Alexander

const keys = Object.keys(input).sort(), result = {};
let i = keys.length;
while(i--) {
  const key = keys[i]
  result[key] = input[key];
}
result;

</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17