Skip to content
Advertisement

Checking similar key pair and then sum it dynamically using reduce

So basically i need to generate a chart, i have the following data

    [
        {
            "indessx": "1",
            "type": "A",
            "number": "260",
            "month": "May",
            "date": "01/05/20"
        },
        {
            "indessx": "2",
            "type": "A",
            "number": "320",
            "month": "May",
            "date": "02/05/20"
        },
{
            "indessx": "2",
            "type": "A",
            "number": "320",
            "month": "June",
            "date": "02/06/20"
        },
    ]

Now, i need to show a graph using the above data, but the response which i am getting have multiple similar values of month like May in the above snippet.Now i used reduce to get the sum of number from a particular month, so like for may it a new object will be generated with the number added up 260 + 320

so the new object of array will be like this..

  [
        {
            "indessx": "1",
            "type": "A",
            "number": "580", // value after addition
            "month": "May",
        },        
{
            "indessx": "2",
            "type": "A",
            "number": "320",
            "month": "June",
            "date": "02/06/20"
        },
    ]

i tried doing this with reduce but stuck on adding a check to see if the month is equal then only add it.

Advertisement

Answer

You can use the following function. As an input, use your initial data, you’ve given at the start. As an output, it returns the array you asked for.

const getNewData = function(data) {
    let indessx = 1, newData = [];
    data.forEach(el => {
        if(newData.findIndex(element => element.month == el.month) != -1) {
            let curElement = newData[newData.findIndex(element => element.month == el.month)];
            curElement.number = (parseInt(curElement.number) + parseInt(el.number)).toString();
            delete curElement.date;
        } else {
            let newEl = el;
            newEl.indessx = indessx;
            newData.push(newEl);
            indessx++;
        };
    });
    return newData;
};
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement