Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count sum of values in JSON array

Having an array like this:

const data = [
    {
        "name": "Dave",
        "coins": 14,
        "weapons": 2,
        "otherItems": 3,
        "color": "red"
    },
    {
        "name": "Vanessa",
        "coins": 18,
        "weapons": 1,
        "otherItems": 5,
        "color": "blue"
    },
    {
        "name": "Sharon",
        "coins": 9,
        "weapons": 5,
        "otherItems": 1,
        "color": "pink"
    },
    {
        "name": "Walter",
        "coins": 9,
        "weapons": 2,
        "otherItems": 4,
        "color": "white"
    }
]

How to count sum of coins, weapons and otherItems using ES6 features? (I'm not attached to this: any simple method would be good.)

data.reduce((first, last) => first + last) generates a chain of [object Object][object Object]s...

like image 980
AbreQueVoy Avatar asked Mar 02 '23 14:03

AbreQueVoy


2 Answers

You have to process every field separately (note that when you don't specify second parameter for reduce it will take first array object as seed and start processing from the second one):

const data = [
    {
        "name": "Dave",
        "coins": 14,
        "weapons": 2,
        "otherItems": 3,
        "color": "red"
    },
    {
        "name": "Vanessa",
        "coins": 18,
        "weapons": 1,
        "otherItems": 5,
        "color": "blue"
    },
    {
        "name": "Sharon",
        "coins": 9,
        "weapons": 5,
        "otherItems": 1,
        "color": "pink"
    },
    {
        "name": "Walter",
        "coins": 9,
        "weapons": 2,
        "otherItems": 4,
        "color": "white"
    }
]

let result = data.reduce((a,c)=> ({ 
     coins: a.coins + c.coins, 
     weapons: a.weapons + c.weapons, 
     otherItems: a.otherItems + c.otherItems })
)

console.log(result);
like image 180
mickl Avatar answered Mar 06 '23 14:03

mickl


You could take an array of wanted keys for the sums and create an object for the sums and add the wanted values.

const
    data = [{ name: "Dave", coins: 14, weapons: 2, otherItems: 3, color: "red" }, { name: "Vanessa", coins: 18, weapons: 1, otherItems: 5, color: "blue" }, { name: "Sharon", coins: 9, weapons: 5, otherItems: 1, color: "pink" }, { name: "Walter", coins: 9, weapons: 2, otherItems: 4, color: "white" }],
    keys = ['coins', 'weapons', 'otherItems'],
    sums = data.reduce(
        (r, o) => (keys.forEach(k => r[k] += o[k]), r), 
        Object.fromEntries(keys.map(k => [k, 0]))
    );

console.log(sums);
like image 32
Nina Scholz Avatar answered Mar 06 '23 16:03

Nina Scholz