Salvatore Difranco
Salvatore Difranco

Reputation: 13

Sort array of object by key in date string format

How can I sort this type of object?

const obj = [{
  "02/10/2021": 291692.14,
  "08/12/2023": 140908.90579999998,
  "09/04/2021": 14.4776,
  "09/06/2023": 863.8189,
  "10/06/2022": 388.9343999999999,
  "10/09/2021": 187.7662,
  "10/12/2021": -85216.4669,
}, {
  "02/10/2021": 189423.30190000002,
  "08/12/2023": 122105.0051,
  "09/04/2021": -0.4682,
  "09/06/2023": 532.7351,
  "10/06/2022": 219.33960000000002,
  "10/09/2021": 581.5980999999999,
  "10/12/2021": -744.8197,
}, ]

As you can read, the keys are date strings, I need to sort the list of objects inside by these keys. e.g:

before sort : {
              "02/10/2021": 291692.14,
              "08/12/2023": 140908.90579999998,
              "09/04/2021": 14.4776,
              "09/06/2023": 863.8189,
              "10/06/2022": 388.9343999999999,
              "10/09/2021": 187.7662,
              "10/12/2021": -85216.4669,
           }

after sort : {
              "09/04/2021": 14.4776,
              "02/10/2021": 291692.14,
              "10/12/2021": -85216.4669,
              "10/06/2022": 388.9343999999999,
              "09/06/2023": 863.8189,
              "08/12/2023": 140908.90579999998,           
           }

I tried a lot of example like this or this one:

(obj).map((val) => {
    Object.entries(val).sort((a, b) => {
      const aa = a[0].split('/').reverse().join();
      const bb = b[0].split('/').reverse().join();
      return aa < bb ? -1 : (aa > bb ? 1 : 0);
    });
  });

Upvotes: 1

Views: 132

Answers (2)

user15388024
user15388024

Reputation:

You can't change the order of the keys in an object but you can convert the entries of an object to an array, sort the array and create a new object with sorted keys. Since ES6 the order the keys is specified.

const data = {
  '02/10/2021': 291692.14, '08/12/2023': 140908.90579999998, '09/04/2021': 14.4776, '09/06/2023': 863.8189, '10/06/2022': 388.9343999999999, '10/09/2021': 187.7662, '10/12/2021': -85216.4669
};


const res = Object
  .entries(data)
  .map(([date, value]) => ({ date, value }))
  .sort(({date: dateA}, {date: dateB}) => new Date(dateA) - new Date(dateB))
  .reduce((acc, el) => ({ ...acc, [el.date]: el.value }), {});

console.log(res)

Upvotes: 0

georg
georg

Reputation: 214969

Your code is almost fine actually, the only missing piece is Object.fromEntries:

sorted = (obj).map(val =>
    Object.fromEntries(
        Object.entries(val).sort((a, b) => {
            const aa = a[0].split('/').reverse();
            const bb = b[0].split('/').reverse();
            return (aa > bb) - (aa < bb);
        })))

Upvotes: 1

Related Questions