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

72
Vistas
Populating an array of object with 0 if object does not exist

I am building a chart for monthly data which would have the x axis as wk1 - wk4 and y axis being the amount of goods etc. I was able to build out a solution but the problem lies when there is no data for a particular week. This is my code below.

    const byAmount = obj => {
    const res = [];
    const keys = Object.keys(obj);
    keys.forEach(key => {
        res.push({
            week: `wk${key}`,
            amount: obj[key]
        });
    });
    return res.sort((a, b) => a.amount - b.amount).slice(0, 5);;
};

const getWeeklyFromMonth = (arr, month) => {
    const week = arr.map(a => ({ ...a, week: Math.floor((moment(a.dateScanned.$date).date() - 1) / 7) + 1 }));
    let dataForMonth = [];
    let total;
    week.map(data => {
        if (moment(data.dateScanned.$date).format("MMM") === month) {
            dataForMonth.push(data);
            const totalPerWeek = dataForMonth.reduce((acc, cur) => {
                acc[cur.week] = acc[cur.week] + cur.amount || cur.amount;
                return acc;
            }, {});
            total = totalPerWeek;
        }
    });


    return byAmount(total);


}

When I run this I get the below:

[
  { week: 'wk1', amount: 14 },
  { week: 'wk2', amount: 27 },
  { week: 'wk4', amount: 43 }
]

This is fine but I want to populate the array with 0 if there is no data say for week 3. I would want it to be this

[
  { week: 'wk1', amount: 14 },
  { week: 'wk2', amount: 27 },
  { week: 'wk3', amount: 0  },
  { week: 'wk4', amount: 43 }
]

I was thinking of having an array of like [1, 2, 3, 4] and if the array includes the week number, pop it out of the array and then the remaining item should be used to populate it but I find myself scratching my head. Does anyone know a decent way to do this?

Thank you in advance.

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

0

You can try this:

const byAmount = obj => {
    const res = [];
    const keys = Object.keys(obj);
    const [min, max] = [Math.min(...keys), Math.max(...keys)];
    for(let key = min; key <= max; key++) {
        res.push({
            week: `wk${key}`,
            amount: obj[key] || 0
        });
    }
    return res.sort((a, b) => a.amount - b.amount).slice(0, 5);;
};
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