Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript reduce to group objects based on condition

Tags:

javascript

I have the following data:

var foo = [
    {'MonthNo' : 03, 'CustomerTypeID' : 1 , 'TotalSales' : 45 },
    {'MonthNo' : 03, 'CustomerTypeID' : 2 , 'TotalSales' : 64 },
    {'MonthNo' : 03, 'CustomerTypeID' : 4 , 'TotalSales' : 89 },
    {'MonthNo' : 03, 'CustomerTypeID' : 5 , 'TotalSales' : 42 },
    {'MonthNo' : 04, 'CustomerTypeID' : 1 , 'TotalSales' : 66 },
    {'MonthNo' : 04, 'CustomerTypeID' : 2 , 'TotalSales' : 78 },
    {'MonthNo' : 04, 'CustomerTypeID' : 5 , 'TotalSales' : 20 },
    {'MonthNo' : 04, 'CustomerTypeID' : 6 , 'TotalSales' : 10 }
];

I want to convert this into the following

{'MonthNo' : 03, 'CustomerTypeID' : 1 , 'TotalSales' : 198 },
{'MonthNo' : 03, 'CustomerTypeID' : 5 , 'TotalSales' : 42 },
{'MonthNo' : 04, 'CustomerTypeID' : 1 , 'TotalSales' : 144 },
{'MonthNo' : 04, 'CustomerTypeID' : 5 , 'TotalSales' : 20 },
{'MonthNo' : 04, 'CustomerTypeID' : 6 , 'TotalSales' : 10 }

For each MonthNo, except for CustomerTypeID 5 & 6, I want to add up the TotalSales value. For Ex: MonthNo 03 for CustomerTypeID 1,2,4 their TotalSales value is summed up to 198.similarly for MonthNo 04, TotalSales value of CustomerTypeID 1 & 2 is added up to 144.

I tried using the reduce function

var result = foo.reduce(function(obj,item){
    // code here
},{});

However , I not able to segregate them to get the desired result.Any help would be appreciated.

like image 568
bikash Avatar asked Oct 30 '22 15:10

bikash


1 Answers

You could check the special cases and use a hash table for referencing the right object for counting.

var foo = [{ MonthNo: '03', CustomerTypeID: 1, TotalSales: 45 }, { MonthNo: '03', CustomerTypeID: 2, TotalSales: 64 }, { MonthNo: '03', CustomerTypeID: 4, TotalSales: 89 }, { MonthNo: '03', CustomerTypeID: 5, TotalSales: 42 }, { MonthNo: '04', CustomerTypeID: 1, TotalSales: 66 }, { MonthNo: '04', CustomerTypeID: 2, TotalSales: 78 }, { MonthNo: '04', CustomerTypeID: 5, TotalSales: 20 }, { MonthNo: '04', CustomerTypeID: 6, TotalSales: 10 }],
    result = foo.reduce(function (hash) {
        return function (r, a) {
            var cType = [5, 6].indexOf(a.CustomerTypeID) === -1 ? 1 : a.CustomerTypeID,
                key = [a.MonthNo, cType].join('|');

            if (!hash[key]) {
                hash[key] = { MonthNo: a.MonthNo, CustomerTypeID: cType, TotalSales: 0 };
                r.push(hash[key]);
            }
            hash[key].TotalSales += a.TotalSales;
            return r;
        }
    }(Object.create(null)), []);
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 61
Nina Scholz Avatar answered Nov 15 '22 04:11

Nina Scholz