tyrell_c tyrell_c - 7 months ago 14
Javascript Question

Using map reduce in javascript

I'm trying to use mapreduce to calculate monthly sales and graph with chart.js later.

Suppose I have a JSON response with fields, amount and date.

For my map function, I took out the month:

month = _.map([items[i].transactionDate], function(date) {
return {
lables: items[i].transactionDate.slice(5,7)
};
});


and for my reduce function ... well I didn't know what to do here.

sum = _.reduce([items[i].amt], function(memo, num) {
return memo + items[i].amt
});


I realized that this will eventually calculate total sum not per month. Problem is that I don't know how to relate the two functions properly.

Edit: Per request, my JSON :

"items": [
{
"_id": "56d1cf3704aee3c68d89cc09",
"amt": 5,
"transactionDate": "2016-02-27T16:30:47.561Z",
}
]


and what I'm trying to get out of this is sales per month on a graph. so far I've been able to project months and total sale but not sales per a specific month.

Answer

I think, simply make one loop with adding new variable

let result= {};

_.forEach(items, (item) => {
    // get month
    let month = item.transactionDate.slice(5,7);
    // get amount
    let amount = item.amt;

    // check if we have this month in finaly object
    if(month in finaly) {
       // added amount
       result[month] += amount;
    } else {
       // if this month doesn't exist added with inital value
       result[month ] = amount;
    }
});

When you can get all amount of certain month or get sum of all months

let allSum = _.reduce(result, (sum, amount) => sum += amount);
let amountInCertainMonth = result["01"];