1๐
โ
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"];
1๐
map
and reduce
are functions of Array that iterate over the array for you
map
returns a new array with the results of the mapping function for each element
var months = items.map ( item => item.transactionDate.slice(5,7) )
and reduce
applies the reducing function to each element and an accumulator.
var sum = items.reduce( (accum, item) => accum + item.amt , 0);
0๐
I assume items[i]
is an object that has .transactionsDate
and .amt
as two arrays with corresponding indices. If so, you can get sales per month and total sales within one reduce
function by starting with { totalSales, months }
.
var chartData = items[i].transactionDate.reduce(function(total, month, index) {
var monthlyData = {
label: month.slice(5, 7),
sales: items[i].amt[index]
};
total.months.push(monthlyData);
total.totalSales += item.amt;
return total;
}, {
totalSales: 0, months: []
});
// get total sales
var totalSales = chartData.totalSales;
// get sales for May starting at index 0
var salesForMay = chartdata.months[4];
Let me know if this is what you were looking for.
0๐
I know this is old, but here is how to use reduce as a group by
var results = items
.map(function(data){
return {"month": data.transactionDate.slice(0,7), "amt": data.amt};
})
.reduce(function(amounts, data){
if (!amounts.hasOwnProperty(data.month))
amounts[data.month] = data.amt;
else
amounts[data.month] = amounts[data.month] + data.amt;
return amounts;
}, {});
Source:stackexchange.com