Skip to content
Advertisement

How to get the sum of specific values in an array contained within another array

I have an object with an array which contains another array. I need to add up the values from these child arrays where the name matches each other.

let arr = {
    expenses: [
        {
            id: 11,
            freqs: [
                { name: "day", value: 100 },
                { name: "week", value: 200 },
                { name: "month", value: 300 },
            ],
        },
        {
            id: 12,
            freqs: [
                { name: "day", value: 100 },
                { name: "week", value: 200 },
                { name: "month", value: 300 },
            ],
        },
        {
            id: 13,
            freqs: [
                { name: "day", value: 100 },
                { name: "week", value: 200 },
                { name: "month", value: 300 },
            ],
        },
    ],
};

In this example, I would need the results:

let result = [
    { name: "day", value: 300 },
    { name: "week", value: 600 },
    { name: "month", value: 900 },
];

I’ve been trying for ages with a combination of filter() and reduce() methods (unsure if these are the right way), but I just can’t get it – it’s really a headscratcher for me! Thank you

Advertisement

Answer

This combines all the freqs into one array then sums their values into an object and then reformats that object to be an array of objects with the name and value keys.

const arr = {"expenses":[{"id":11,"freqs":[{"name":"day","value":100},{"name":"week","value":200},{"name":"month","value":300}]},{"id":12,"freqs":[{"name":"day","value":100},{"name":"week","value":200},{"name":"month","value":300}]},{"id":13,"freqs":[{"name":"day","value":100},{"name":"week","value":200},{"name":"month","value":300}]}]};

const res = Object.entries(
  arr.expenses
    .flatMap(({ freqs }) => freqs)
    .reduce(
      (acc, { name, value }) => Object.assign(acc, { [name]: (acc[name] ?? 0) + value }),
      {}
    )
).map(([name, value]) => ({ name, value }));

console.log(res);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement