0

I have the following JSON structure.

var fooArray =
    [{ name: 'firstValue',
     price1: 20,
     price2: 11
    },
    {  name: 'secondValue',
     price1: 54,
     price2: 13
    },
    {  name: 'thirdValue',
     price1: 3,
     price2: 6
    }]

How can I sum up the values in the object array? (other than using a for loop)

{price1: 77,
 price2: 28}

2 Answers 2

2

This is similar to @MatthewMcveigh's answer, but the resulting object does not have a spurious name property:

_.reduce(fooArray, function (accum, x) {
    return { 
        price1: x.price1 + accum.price1, 
        price2: x.price2 + accum.price2
    };
}, {price1: 0, price2: 0});
Sign up to request clarification or add additional context in comments.

Comments

1

You can reduce over the array with a function that sums the properties:

_.reduce(fooArray, function (accum, x) {
    return { 
        price1: x.price1 + accum.price1, 
        price2: x.price2 + accum.price2
    };
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.