Nikeeta kurrey
Nikeeta kurrey

Reputation: 103

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.

Upvotes: 2

Views: 252

Answers (1)

Phil
Phil

Reputation: 165069

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)
}

Upvotes: 2

Related Questions