Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda