'Underscore js group by each month on each year in single level

This question is the extention of this question. which is here Underscore js group by each month on each year This is giving the expected result and the code which i am using is here.

   const months = [
        'jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'
    ]
    const result = flashMessage.reduce((res:any, item:any) => {
        const date = new Date(item.created_at)
        const year = date.getFullYear();
        const month = months[date.getMonth()];
        const existingYear = res[year] || {}
        res[year] = existingYear
        const updated  = [...(existingYear[month] || []), item]
        res[year][month] = updated
        return res
     }, {});

This is the answer which it is producing now.

{
  "2022": {
    "jan": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      },
      {
        "id": 2,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      },
      {
        "id": 1,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      }
    ]
  }
}

What if i want the result in a single level.

{
  "2022 jan": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      }
      {
        "id": 2,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      },
      {
        "id": 1,
        "created_by": 1,
        "created_at": "2022-01-31T07:00:01.880Z"
      }
    ]
  "2022 feb": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2022-02-31T07:00:01.880Z"
      }
    ]
  "2021 feb": [
      {
        "id": 3,
        "created_by": 1,
        "created_at": "2021-02-31T07:00:01.880Z"
      }
    ]
}

Is there any way i can do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source