javascript - 根据数组中的小时计算日期的出现次数

标签 javascript jquery arrays datetime

我有以下方法 -

// Push the date values into dateArray
var dateArray = [];

    $.each(dateHtml, function (i, el) {
                dateArray.push(htmlDateValue);
        }
    });

然后按最早日期排序 -

// sort array to have earliest date first
    dateArray.sort(function (a, b) {
        return new Date(b.date) - new Date(a.date);
    });

给我留个例子 -

dateArray = 
["02/10/2015 00:00:07", 
"02/10/2015 00:00:08", 
"02/10/2015 01:00:03",
"02/10/2015 01:00:05",
"02/10/2015 02:00:14",
"03/10/2015 07:00:37"];

我创建了 var arrOfCounts = [];,我想用每个中存在的每个小时的计数值来填充它。

例如,在上述数组中,结果应该是 -

arrOfCounts  = 
[2,  // 2 instances of values within the hour of 00:00:00 on the 02/10/2015
 2,  // 2 instances of values within the hour of 01:00:00 on the 02/10/2015
 1,  // 1 instances of values within the hour of 02:00:00 on the 02/10/2015
 1]; // 1 instances of values within the hour of 07:00:00 on the 03/10/2015

所以我开始循环 dateArray 中的每个值 -

$.each(dateArray, function (i, el) {

                    // Here I have to establish the value of count
                    arrOfCounts.push(count);
            }
        });

我怎样才能实现这个目标?

最佳答案

使用代表日期和时间的键创建自定义对象

var dates = ["02/10/2015 00:00:07",
  "02/10/2015 00:00:08",
  "02/10/2015 01:00:03",
  "02/10/2015 01:00:05",
  "02/10/2015 02:00:14",
  "03/10/2015 07:00:37"
];
var counts = {};

dates.forEach(function(date) {
  var dateS = date.split(' ')[0];
  var hour = new Date(date).getHours();

  if (typeof counts[dateS] == 'undefined') {
    counts[dateS] = {};
  }

  if (typeof counts[dateS][hour] == 'undefined') {
    counts[dateS][hour] = 0;
  }

  counts[dateS][hour] += 1;
});

console.log(counts);

关于javascript - 根据数组中的小时计算日期的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32908738/

相关文章:

python - 用数组索引多维数组

java - 尝试使用构造函数传递数组值

java - 如何从java中保存数据库值的字符串数组计算一小时前的时间

javascript - 函数不返回任何内容(甚至没有未定义)

javascript - 在用户访问网站而不是单个页面 60 秒后运行功能

javascript - 如何动态设置工具提示宽度?

javascript - 每 x 次 AngularJS 隐藏和显示 div

jquery - 使用 HTML ID 作为数组

c# - 通知主机更改

JavaScript:通过双击禁用文本选择