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

156
Views
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 answers
Answer question

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 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!