我的 javascript 数组就是这样。
var datearray = [
"2016-01-13",
"2016-01-18",
"2016-01-30",
"2016-02-13",
"2016-02-18",
"2016-02-28",
"2016-03-13",
"2016-03-23",
"2016-03-30",
"2016-04-13",
"2016-04-18",
"2016-04-30",
"2016-05-13",
"2016-05-18",
"2016-05-28",
"2016-06-13",
"2016-06-23",
"2016-06-30",
"2016-08-22"
]
但我的搜索日期是 startDate = 2015-12-01;
和 endDate = 2016-09-30;
我想获取上述之间的新日期数组 开始日期
和结束日期
。这个新数组将像这样显示,
var newOjArray = [
{"2015-12":"0"},
{"2016-01":"3"},
{"2016-02":"3"},
{"2016-03":"3"},
{"2016-04":"3"},
{"2016-05":"3"},
{"2016-06":"3"},
{"2016-07":"0"},
{"2016-08":"1"},
{"2016-09":"0"}
];
值表示考虑日期范围的总数。我是如何创建它的。
最佳答案
完整的提案。使用具有所需分组结果的数组。
function getGroupedData(dates, from, to) {
function pad(s, n) { return s.toString().length < n ? pad('0' + s, n) : s; }
var temp = Object.create(null),
result = [],
fromYear = +from.slice(0, 4),
fromMonth = +from.slice(5, 7),
toYear = +to.slice(0, 4),
toMonth = +to.slice(5, 7),
o, k;
datearray.forEach(function (d) {
var k = d.slice(0, 7);
temp[k] = (temp[k] || 0) + 1;
});
while (true) {
k = pad(fromYear, 4) + '-' + pad(fromMonth, 2);
o = {};
o[k] = (temp[k] || 0).toString();
result.push(o);
if (fromYear === toYear && fromMonth === toMonth) {
break;
}
fromMonth++;
if (fromMonth > 12) {
fromMonth = 1;
fromYear++;
}
}
return result;
}
var datearray = ["2016-01-13", "2016-01-18", "2016-01-30", "2016-02-13", "2016-02-18", "2016-02-28", "2016-03-13", "2016-03-23", "2016-03-30", "2016-04-13", "2016-04-18", "2016-04-30", "2016-05-13", "2016-05-18", "2016-05-28", "2016-06-13", "2016-06-23", "2016-06-30", "2016-08-22"];
console.log(getGroupedData(datearray, '2015-12-01', '2016-09-30'));
关于javascript - 如何使用日期数组javascript创建计数对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37988786/