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

234
Vistas
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 Respuestas
Responde la pregunta

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