Esta pregunta es una extensión de esta pregunta aquí. Subrayar el grupo js por cada mes en cada año en un solo nivel
El código que estoy usando está aquí.
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 }, {});El código anterior está produciendo el resultado esperado, pero está fuera de servicio. Aquí está el resultado del código anterior. [![ingrese la descripción de la imagen aquí][1]][1]
Quiero que el resultado esté en orden. El orden que quería se muestra a continuación.
marzo 2022
febrero 2022
enero 2022
marzo 2021
febrero 2021
enero 2021
Entonces, ¿cómo puedo hacer eso? [1]: https://i.stack.imgur.com/BS9ZS.png
Esta puede ser una posible solución para lograr el objetivo deseado.
// '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]) });Acercarse
result.sort()sortedKeys.sort emplea el objeto de result created_at prop correspondiente al valor de cada key .sortedKeys usando .forEach y muestre la clave k y el valor correspondiente del objeto de result .Fragmento de código
A continuación, se proporciona un ejemplo de trabajo de las claves ordenadas generadas
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]) });