lodash:根据日期聚合和减少对象数组

时间:2016-04-06 14:47:54

标签: javascript arrays functional-programming lodash

我是Lodash和功能编程概念的新手。所以,我有一系列具有日期日期的对象:

[
    {
         "date": '1-Jan-2015',
         "count": 4 
    },
    {
         "date": '4-Jan-2015',
         "count": 3 
    },
    {
         "date": '1-Feb-2015',
         "count": 4 
    },
    {
         "date": '18-Feb-2015',
         "count": 10 
    }
]

我希望减少和聚合它,以便获得一个对象数组,其中每个对象都有月度数据,而不是像这样的日常数据:

[
    {
        "date": 'Jan, 2015',
        "count": 7 // aggregating the count of January
    },
    {
        "date": 'Feb, 2015',
        "count": 14 //aggregating the count of February
    }
]

目前,我写了一个非常难以理解和复杂的代码,其中包含ifs和fors。但是,我想用lodash重构它。是否有可能使用lodash?我环顾四周,找到了_.reduce_.groupBy,我可以使用它,但我现在很难过,无法找到一个干净的实施方案。

2 个答案:

答案 0 :(得分:3)

你不需要lodash来实现你想要的,你可以使用普通的旧Javascript:

var array = [{
  "date": '1-Jan-2015',
  "count": 4
}, {
  "date": '4-Jan-2015',
  "count": 3
}, {
  "date": '1-Feb-2015',
  "count": 4
}, {
  "date": '18-Feb-2015',
  "count": 10
}]

var result = array.reduce(function(ar, item) {
  var index = item.date.split('-').slice(1,3).join(', ') //getting date Month-Year
  _item = ar.filter(function(a) { 
    return a.date === index
  })[0] // getting item if already present in array

  // getting index of _item if _item is already present in ar
  indexOf = ar.indexOf(_item) 

  if(indexOf > -1)
    // we sum the count of existing _item
    ar[indexOf] = {date: index, count: count: _item.count + item.count } 
  else
    // item is not yet in the array, we push a new _item
    ar.push({date: index, count: item.count}) 

  return ar; // return the array as required by reduce
}, []) // initialize the reduce method with an empty array

console.log(result) // your array with aggregated dates

有趣的是,lodash版本:

_.values(array.reduce(function(obj, item) {
  var index = item.date.split('-').slice(1, 3).join(', ')
  obj[index] = {date: index, count: (obj[index] && obj[index].count || 0) + item.count}
  return obj
}, {}))

请参阅jsfiddle here

答案 1 :(得分:3)

我们可以使用_.reduce& _.values

var arr = [
    {
         "date": '1-Jan-2015',
         "count": 4 
    },
    {
         "date": '4-Jan-2015',
         "count": 3 
    },
    {
         "date": '1-Feb-2015',
         "count": 4 
    },
    {
         "date": '18-Feb-2015',
         "count": 10 
    }
]

_.values(_.reduce(arr,function(result,obj){
  var name = obj.date.split('-');
  name = name[1]+', '+name[2];  
  result[name] = {
    date:name,
    count:obj.count + (result[name]?result[name].count:0)
  };
  return result;
},{}));