在javascript中计算具有特定日期的数组元素

Max*_*Max 1 javascript date counting

我在 javascript 中有一个 Date() 对象数组,我想计算每天的事件数。

下面是一个例子:

我所拥有的是:

Array [ Date 2014-12-04T10:30:20.000Z, Date 2014-12-05T11:04:58.056Z, Date 2014-12-05T11:04:58.056Z, Date 2014-12-05T11:04:58.056Z ]
Run Code Online (Sandbox Code Playgroud)

我想要的是:

Array [{date: '2014-12-04', counts: 1}, {date: '2014-12-05', counts: 3}]
Run Code Online (Sandbox Code Playgroud)

非常感谢!

最大限度

dei*_*tch 6

基本答案:

var arr = [], // fill it with array with your data
results = {}, rarr = [], i, date;

for (i=0; i<arr.length; i++) {
  // get the date
  date = [arr[i].getFullYear(),arr[i].getMonth(),arr[i].getDate()].join("-");
  results[date] = results[date] || 0;
  results[date]++;
}
// you can always convert it into an array of objects, if you must
for (i in results) {
  if (results.hasOwnProperty(i)) {
     rarr.push({date:i,counts:results[i]});
  }
}
Run Code Online (Sandbox Code Playgroud)

使用 lodash 函数可以使这些变得更容易,并且Array.forEach()在 ES5 中