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

233
Views
How to count by Month in Nodejs?

My question is how to get total number of id's created per month. The below is my code fetching response from Mysql Db.

const dashboardOverview = async (req,res,next) => {
 var ordersPerMonth = await Orders.findAll({attributes:['od_id','od_created_date']});
     for(var i = 0; i < ordersPerMonth.length ; i++){
        let dataItem = {};
        for(const [key,value] of Object.entries(ordersPerMonth[i].dataValues)){
            dataItem[key.replace("od_","")] = value;
        }
        dataStore.push(dataItem);
    }
    console.log(dataStore)

    const arr = dataStore;
    console.log(arr)
    const counts = arr.reduce((m, { created_date }) => {
        // Create a key from the year and month, eg "2021-08"
        const key = created_date.substr(0, 7)
        
        // Increment the count for the key
        return m.set(key, (m.get(key) ?? 0) + 1)
      }, new Map())
      
      console.log(Object.fromEntries(counts))
}

Now in response I wanted monthname and total count of orders placed that month. For ex- [ January-21 : 23, February-21: 45......December-21: 56] But while using reduce() function I am getting type error:arr.reduce is not a function. I hope my query is clear.

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

0

This kind of result can be achieved by reducing your array to a map of month counts.

const formatter = new Intl.DateTimeFormat("en", {
  year: "2-digit",
  month: "long",
})

const formatKey = date => formatter.format(date).replace(" ", "-")

const dashboardOverview = async (req, res, next) => {
  const orders = await Orders.findAll({
    attributes: ["od_id", "od_created_date"]
  })

  const ordersPerMonth = orders.reduce((map, { od_created_date }) => {
    // assuming od_created_date is already a `Date` instance
    const key = formatKey(od_created_date).replace(" ", "-")

    return map.set(key, (map.get(key) ?? 0) + 1)
  }, new Map())

  const asObject = Object.fromEntries(ordersPerMonth)

  console.log(asObject)

  // and if you want to respond with JSON
  res.json(asObject)
}
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!