Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
How to group by dynamic key value of an object of arrays(Month and year)

This question is an extention of this question here. Underscore js group by each month on each year in single level

The code which i am using is here.

        const months = [
            'January','February','March','April','May','June','July','August','September','October','November','December'
        ]
        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[`${month} ${year}`] ||[]; 
            const updated  = [...(existingYear[month] || []), item]
            const returnItem = {
                title:item.title,
                user_message:item.user_message,
                created_at:item.created_at
            };
            res[`${month} ${year}`] = [...existingYear,returnItem]
            return res
        }, {});

The above code is producing expected result but it is in out of order here is the result of the above code. [![enter image description here][1]][1]

I want the result is in order. The order which i wanted is shown below.

March 2022

February 2022

January 2022

March 2021

February 2021

January 2021

So on how can i do that? [1]: https://i.stack.imgur.com/BS9ZS.png

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This may be one possible solution to achieve the desired objective.

// 'sortedKeys' will hold only the keys of the 'res' object
// but these will be in a sorted-order (based on prop 'created_at')
const sortedKeys = [
    ...Object.keys(result)
  ].sort(
    (a, b) => (
      result[a][0]['created_at'] > result[b][0]['created_at']
      ? -1
      : 1
    )
);

// to render in the sorted order, use 'sortedKeys' like this
sortedKeys.forEach(k => {
  console.log('key: ', k, ' value: ', result[k])
});

Approach

  • First obtain the keys from result object
  • Next, spread them and then apply .sort()
  • Sorted array is stored in sortedKeys array
  • The .sort employs the result object's created_at prop corresponding to the value of each key.
  • To validate the sort, iterate over the sortedKeys array using .forEach and display the key k and the corresponding value from result object.

Code Snippet

The below provides a working-example of the sortedKeys generated

const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const flashMessage = [
  {
    created_at: '2021-03-11T06:40:46.790Z',
    title: 'Announcement 02',
    user_message: 'see more test',
  }, {
    created_at: '2021-01-11T06:40:46.790Z',
    title: 'Announcement 25',
    user_message: 'see more test',
  }, {
    created_at: '2021-02-11T06:40:46.790Z',
    title: 'This is a push notification to all',
    user_message: 'A push notification to all'
  }, {
    created_at: '2022-01-11T06:40:46.790Z',
    title: 'title for jan 2021',
    user_message: 'message for jan 2021'
  }, {
    created_at: '2022-03-11T06:40:46.790Z',
    title: 'title for mar 2021',
    user_message: 'message for mar 2021'
  }, {
    created_at: '2022-02-11T06:40:46.790Z',
    title: 'title for feb 2021',
    user_message: 'message for feb 2021'
  }
];

const result = flashMessage.reduce((res, item) => {
  const date = new Date(item.created_at)
  const year = date.getFullYear();
  const month = months[date.getMonth()];
  const existingYear = res[`${month} ${year}`] || [];
  const updated = [...(existingYear[month] || []), item]
  const returnItem = {
    title: item.title,
    user_message: item.user_message,
    created_at: item.created_at
  };
  res[`${month} ${year}`] = [...existingYear, returnItem]
  return res
}, {});

const sortedKeys = [
  ...Object.keys(result)
].sort(
  (a, b) => (
    result[a][0]['created_at'] > result[b][0]['created_at']
    ? -1
    : 1
  )
);

console.log('keys of result object sorted: ', sortedKeys);

sortedKeys.forEach(k => {
  console.log('key: ', k, ' value: ', result[k])
});

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!