Home > Blockchain >  How to Add the values ​of an object array based on a condition? JS
How to Add the values ​of an object array based on a condition? JS

Time:05-28

I am looking to sum the fields of my objects according to a value of my object

For example, i have an array:

   [
    {
        "month": 4,
        "periodDays": 1,
        "expected": 5
    },
    {
        "month": 5,
        "periodDays": 10,
        "expected": 40
    },
    {
        "month": 5,
        "periodDays": 11,
        "expected": 35
    },

    {
        "month": 6,
        "periodDays": 8,
        "expected": 20
    }
]

and i want:

  [
{
    "month": 4,
    "periodDays": 1,
    "expected": 5
},
{
    "month": 5,
    "periodDays": 21,
    "expected": 75
},
{
    "month": 6,
    "periodDays": 8,
    "expected": 20,
},

I know I can use the reducer but I can't make it work with a condition.

CodePudding user response:

You can use Array.reduce() to create the desired result.

We start by creating a map using the month value as the key. We then initialize the periodDays and expected values to zero.

For each object, we then add the periodDays and expected to get the sum for each.

Finally, we use Object.values() to turn our map into an array:

let input = [ { "month": 4, "periodDays": 1, "expected": 5 }, { "month": 5, "periodDays": 10, "expected": 40 }, { "month": 5, "periodDays": 11, "expected": 35 },  { "month": 6, "periodDays": 8, "expected": 20 } ]

const result = Object.values(input.reduce((acc, { month, periodDays, expected }) => { 
    acc[month] = acc[month] || { month, periodDays: 0, expected: 0 };
    acc[month].periodDays  = periodDays;
    acc[month].expected  = expected;
    return acc;
}, {}));

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

  • Related