Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
How to groud data array from backend by date Month

I am currently creating an animal shelter web app using mern and i have trouble grouping data by date month. so i have this schema for the rescued date:

const animalSchema = new mongoose.Schema({
  date_rescued: {
        type: Date,
        default: Date.now,
    },
})
module.exports = mongoose.model('Animal', animalSchema);

And here on my animal controller backend this is my query for fetching the datas:

exports.getRescuedChart = async(req,res,next) => {
    const rescuedanimals = await Animal.find({}).select(['date_rescued']);
    res.status(200).json({
        success:true,
        rescuedanimals,
    })
}

the data that this function is returning to the state is this: enter image description here

what i want to have is group them by data and count how many object has the same date.

rescuedanimals =[ {
date_rescued: "April", animal_count: 8 } ]

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

so yeah i just learn how to do it myself so here's what i did.

first is that i installed dataeformat library: 'npm install dateformat' i import it on my project: import dateFormat from 'dateformat';

what i did first is to change the date format and reduce duplicate dates.

const groups = rescuedanimals.reduce(
            (groups, rescued_animal) => {
                const date = dateFormat(rescued_animal.date_rescued[0], "mmmm")
                if (!groups[date]) {
                    groups[date]=[]
                }
                groups[date].push(rescued_animal);
                return groups;
            }, {}
        )

after that i created a new function to put this on an arraay and also to get the legnth of the objects that are in that date.

const groupArrays = Object.keys(groups).map((date) => {
        return {
            date,
            games: groups[date].length
        };
    });

thanks to Austin Greco: https://stackoverflow.com/a/46802505/12398637

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda