我在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 ]
我想要的是:
Array [{date: '2014-12-04', counts: 1}, {date: '2014-12-05', counts: 3}]
非常感谢!
最大限度
基本答案:
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]});
}
}
使用lodash函数和Array.forEach()
ES5可以使这些操作变得更加容易
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句