Search code examples
javascriptarraysobjectecmascript-6lodash

How to get total of values in array of javascript objects


I have the following array:

[
{genderAge: "Male 25-39", count: 13029, weightedCount: 18475.6824262314, matchingSegment: 2},
{genderAge: "Female 55+", count: 35639, weightedCount: 32294.5926147014, matchingSegment: 8},
{genderAge: "Female 25-39", count: 23285, weightedCount: 20645.0599977815, matchingSegment: 6},
{genderAge: "Female 18-24", count: 7745, weightedCount: 8497.30029399032, matchingSegment: 5},
{genderAge: "Male 55+", count: 38018, weightedCount: 28589.2793936886, matchingSegment: 4},
{genderAge: "Male 18-24", count: 4038, weightedCount: 8122.65161312996, matchingSegment: 1},
{genderAge: "Female 40-54", count: 23051, weightedCount: 22834.3167597392, matchingSegment: 7},
{genderAge: "Male 40-54", count: 17278, weightedCount: 19681.8852663563, matchingSegment: 3}
]

I want to transform this array of objects into an array with two objects containing the summed up data (count, weightedCount and matchingSegment) for Males and Females. Is there a shorthand way of achieving this using Lodash and/or ES6?

update: Apologies I provided the wrong data.


Solution

  • You can use reduce method

    var list = [
    {genderAge: "Male 25-39", count: 13029, weightedCount: 18475.6824262314, matchingSegment: 2},
    {genderAge: "Female 55+", count: 35639, weightedCount: 32294.5926147014, matchingSegment: 8},
    {genderAge: "Female 25-39", count: 23285, weightedCount: 20645.0599977815, matchingSegment: 6},
    {genderAge: "Female 18-24", count: 7745, weightedCount: 8497.30029399032, matchingSegment: 5},
    {genderAge: "Male 55+", count: 38018, weightedCount: 28589.2793936886, matchingSegment: 4},
    {genderAge: "Male 18-24", count: 4038, weightedCount: 8122.65161312996, matchingSegment: 1},
    {genderAge: "Female 40-54", count: 23051, weightedCount: 22834.3167597392, matchingSegment: 7},
    {genderAge: "Male 40-54", count: 17278, weightedCount: 19681.8852663563, matchingSegment: 3}
    ]
    
    list.reduce(function(a, b) {
         if(/^Male/.test(b['genderAge'])) {
            a['male']['pop'] += b['count'];
            a['male']['matchingSegment'] += b['matchingSegment'];
            a['male']['weightedCount'] += b['weightedCount'];
        } else if(/^Female/.test(b['genderAge'])){
            a['female']['pop'] += b['count'];
            a['female']['matchingSegment'] += b['matchingSegment'];
            a['female']['weightedCount'] += b['weightedCount'];
        }
         return a;
    }, {'male':{'pop':0, 'matchingSegment':0, 'weightedCount':0}, 'female':{'pop':0, 'matchingSegment':0, 'weightedCount':0}});