Monday, 19 April 2021

Group Array of Objects based on combination of Year and Month

i Have an Array of Objects Like this:

The array is sorted based on the date:

//My Actual React Context Dates are built with Date() and like this: Fri Apr 16 2021 13:22:24 GMT+0430 (Iran Daylight Time)
  
  const transactions =  [
    {
        "amount": 42,
        "text": "",
        "date": "2021-04-16T08:52:24.408Z",
        "type": "Expense",
        "category": "Car",
        "id": "dda58c24-92fc-431f-a4eb-d89fad5cdf81"
    },
    {
        "amount": 3000,
        "text": "",
        "date": "2021-04-14T19:30:00.000Z",
        "type": "Income",
        "category": "Salary",
        "id": "915db4d8-1b20-4455-be06-c50b15920ae8"
    },
    {
        "amount": 2997,
        "text": "",
        "date": "2021-03-17T20:30:00.000Z",
        "type": "Income",
        "category": "Salary",
        "id": "ec1608b1-dc4f-428d-9d41-006322b2cf78"
    },
   
    {
        "amount": 19993,
        "text": "",
        "date": "2021-02-01T20:30:00.000Z",
        "type": "Income",
        "category": "Salary",
        "id": "5f51a268-4d68-4407-87f2-3156d27d5084"
    },
    {
        "amount": 1000,
        "text": "",
        "date": "2021-01-06T20:30:00.000Z",
        "type": "Expense",
        "category": "Salary",
        "id": "554b0776-8fad-46da-9609-e617f33b4e0e"
    },
    {
        "amount": 96,
        "text": "",
        "date": "2020-08-06T19:30:00.000Z",
        "type": "Income",
        "category": "Salary",
        "id": "1b806abf-9012-477f-9f1b-c99c53e1cb7d"
    }]

  const formatedDate = transactions.map((item) => {
    return {
      ...item,
      year: item.date.getFullYear(),
      month: item.date.getMonth(),
    };
  });

Final Design

I have two questions:

  1. How can I group them by Year and month?
  2. How can I map over sorted and grouped output and make my page?

I found out that if I group them as One Object because objects can not be sorted I can't iterate over them.



from Group Array of Objects based on combination of Year and Month

No comments:

Post a Comment