Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  { 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.

>Solution :

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);;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading