Home > Net >  How to do grouping by in JS?
How to do grouping by in JS?

Time:01-24

I have an API which returns a JSON object like this:

plans: [{
    0 : {plan: "gold", amount: 5000},
    1: {plan: "silver", amount: 2000},
    3: {plan: "silver", amount: 1000},
    4: {plan: "gold", amount: -4000}
}]

I want to group the result by plan. So here is the expected result:

groupedPlans: [{
    "gold" : {amount: 1000},
    "silver" : {amount: 3000}
}]

Is it possible to do such a thing using JS? I know in other languages like SQL you can do that simply by using GROUP BY plan. But not sure how can I do that in JS.

CodePudding user response:

You could get a flat array and group by plan.

const
    plans = [{ 0: { plan: "gold", amount: 5000 }, 1: { plan: "silver", amount: 2000 }, 3: { plan: "silver", amount: 1000 }, 4: { plan: "gold", amount: -4000 } }],
    result = plans
        .flatMap(Object.values)
        .reduce((r, { plan, amount }) => {
            (r[plan] ??= { amount: 0 }).amount  = amount;
            return r;
        }, {});

console.log(result);

  • Related