如何按日期计算对象数组中的出现次数

How to count occurrences in an array of objects by date

我正在 TypeScript 或 JavaScript 中搜索一个强大的解决方案来计算对象数组中的出现次数。我想在 Date 之前完成。 (我需要它来创建一些图表)

例如,我有这个数组:

var arr = [
    {date: Wed Jan 20 2016 
        type: "Apples"}, 
    {date: Mon Feb 29 2016
        type: "Peaches"},
    {date: Thu Mar 31 2016 
        type: "Apples"},
    {date: Fri Apr 22 2016 
        type: "Apples"},
    {date: Fri Apr 22 2016 
        type: "Apples"},
    {date: Fri Apr 22 2016 
        type: "Apples"},
    {date: Fri Apr 22 2016 
        type: "Strawberries"}
]

我想要的结果是下一个:

var arr2 = [
        {date: Wed Jan 20 2016 
            type: ["Apples", 1]}, 
        {date: Mon Feb 29 2016
            type: ["Peaches",1]},
        {date: Thu Mar 31 2016 
            type: ["Apples",1]},
        {date: Fri Apr 22 2016 
            type: ["Apples",3],["Strawberries",1]}
    ]

不知道为什么,找不到好的解决方法,这几天一直在研究中...

如果有人知道技巧、函数或其他东西?

过滤数组并在过滤函数中检查日期。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

function findItemsByDate(value) {
    // find if an item already exists with the date index
    var dateIndex = arr2.findIndex(findDateIndex);
    // create an array or use the existing one based on result
    if(dateIndex === -1){
      var dateArray = []
    }else{
      dateArray = arr2[dateIndex];
    }
    // find the type object based on the input type and add to it, or create a new one.
    if(dateArray.type.hasOwnProperty(value.type)){
       dateArray.type[value.type] += 1;
    }else{
      dateArray.type[value.type] = 1;
    }
}
// utility function to see if an item already exists in the new array with the key for the date.
function findDateIndex(item, index, arr){
        if(item.date = "Thu Mar 31 2016"){
            alert("Has Data")
        return index;
    }
    return -1;
  }

这将 return 与您正在寻找的结果略有不同,但更易于管理。

var arr2 = [
        {date: "Wed Jan 20 2016", type: ["Apples", 1]}, 
        {date: "Mon Feb 29 2016",type: ["Peaches",1]},
        {date: "Thu Mar 31 2016", type: ["Apples",1]},
        {date: "Fri Apr 22 2016", type: {"Apples":3,"Strawberries":1}}
    ]

应该像这样工作:

var x = new Date().getTime(),
    filtered = arr.filter( function (obj) { return obj.date.getTime() >= x }),
    occurenceCount = filtered.length;

我使用 getTime() 将日期转换为整数,因为我比较 Date 对象时有奇怪的行为。 arr2 将包含 x 之后的所有日期(在此示例中为 NOW)并且计数将 return arr2 中包含的元素数。

试试这个

先创建地图

var map = {}; arr.forEach(function(val){
  map[val.date] = map[val.date] || {};
  map[val.date][val.type] = map[val.date][val.type] || 0;
  map[val.date][val.type]++;
});

现在得到输出

var output = Object.keys(map).map(function(key){
  var tmpArr = [];
  for(var type in map[key])
  {
     tmpArr.push( [ type, map[key][type] ] )
  }
  return { date : key, type: tmpArr  };
})

演示

var arr = [
    {date: "Wed Jan 20 2016",
        type: "Apples"}, 
    {date: "Mon Feb 29 2016",
        type: "Peaches"},
    {date: "Thu Mar 31 2016",
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Strawberries"}
]


    var map = {}; arr.forEach(function(val){
      map[val.date] = map[val.date] || {};
      map[val.date][val.type] = map[val.date][val.type] || 0;
      map[val.date][val.type]++;
    });


    var output = Object.keys(map).map(function(key){
      var tmpArr = [];
      for(var type in map[key])
      {
         tmpArr.push( [ type, map[key][type] ] )
      }
      return { date : key, type: tmpArr  };
    })

    document.body.innerHTML += JSON.stringify(output,0,4);

使用适当的日期格式(如此处的 ISO 日期)和临时对象,您可以使用 Array#forEach 循环和 return 想要的结果。它在一个循环中工作。

var array = [{ date: '2016-01-20', type: "Apples" }, { date: '2016-02-29', type: "Peaches" }, { date: '2016-03-31', type: "Apples" }, { date: '2016-04-22', type: "Apples" }, { date: '2016-04-22', type: "Apples" }, { date: '2016-04-22', type: "Apples" }, { date: '2016-04-22', type: "Strawberries" }],
    grouped = [];

array.forEach(function (a) {
    var key = a.date + '|' + a.type;
    if (!this[a.date]) {                
        this[a.date] = { date: a.date, type: [] };;
        grouped.push(this[a.date]);
    }            
    if (!this[key]) {
        this[key] = [a.type, 0];
        this[a.date].type.push(this[key]);
    }
    this[key][1]++;
}, Object.create(null));

document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');