简体   繁体   English

在JavaScript中使用Map Reduce

[英]Using map reduce in javascript

I'm trying to use mapreduce to calculate monthly sales and graph with chart.js later. 我稍后尝试使用mapreduce来计算每月销售额和带有chart.js的图表。

Suppose I have a JSON response with fields, amount and date. 假设我有一个包含字段,金额和日期的JSON响应。

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. 以及我的reduce函数...我不知道该怎么办。

  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 : 编辑:每个请求,我的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. 到目前为止,我已经能够预测月份和总销售额,但无法预测特定月份的销售额。

map and reduce are functions of Array that iterate over the array for you mapreduce是Array的函数,可为您迭代数组

map returns a new array with the results of the mapping function for each element map返回一个新数组,其中包含每个元素的映射函数结果

var months = items.map ( item => item.transactionDate.slice(5,7) )

and reduce applies the reducing function to each element and an accumulator. reduce将缩减功能应用于每个元素和一个累加器。

var sum = items.reduce( (accum, item) => accum + item.amt , 0);

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"];

I assume items[i] is an object that has .transactionsDate and .amt as two arrays with corresponding indices. 我假设items[i]是一个对象,它具有.transactionsDate.amt作为具有相应索引的两个数组。 If so, you can get sales per month and total sales within one reduce function by starting with { totalSales, months } . 如果是这样,您可以从{ totalSales, months }开始,在一个reduce函数中获得每月销售额和总销售额。

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. 让我知道这是否是您想要的。

I know this is old, but here is how to use reduce as a group by 我知道这很老了,但是这是如何按组使用reduce

  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; }, {}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM