我有一个具有不同时间戳的对象数组,它们是来自 MomentJS 的 Moment-Objects。
[
{
"name": "A",
"eventDateTime": "2016-12-09 07:50:17",
},
{
"name": "B",
"eventDateTime": "2016-12-09 06:50:17",
},
{
"name": "C",
"eventDateTime": "2016-12-09 07:01:17",
}
]
现在我需要做的(通常有更多这些对象)是首先对它们进行排序,然后按 15 分钟的间隔进行分组。
如此排序,我应该得到
[
{
"name": "B",
"eventDateTime": "2016-12-09 06:50:17",
},
{
"name": "C",
"eventDateTime": "2016-12-09 07:01:17",
},
{
"name": "A",
"eventDateTime": "2016-12-09 07:50:17",
}]
然后我需要从时间为 06:50:17 的第一个对象开始对它们进行分组。因此,这将是我应添加所有对象的第一组,即 06:50:17 到 07:05:17 之间的对象。由于数组已排序,我可以迭代直到一个对象早于 07:05:17。
总而言之,这并不难实现,但它应该尽可能高效。我们使用 Lodash.js,它有很多功能。我知道 groupBy 方法,但不知道如何 A)使用 MomentJS 和 B)在其中定义一个函数,该函数检查间隔。
你们有什么建议吗?
最佳答案
var data = [{
"name": "A",
"eventDateTime": "2016-12-09 07:50:17",
}, {
"name": "B",
"eventDateTime": "2016-12-09 06:50:17",
}, {
"name": "C",
"eventDateTime": "2016-12-09 07:01:17",
}];
var sortedDate = _.sortBy(data, function(o) {
return o.eventDateTime;
});
var groupTime = null; // new Date(new Date(sortedData[0].eventDateTime).getTime() + 15 * 60000);
var groupedData = _.groupBy(sortedDate, function(d) {
// no need to do this if eventDateTime is already a Date object
var time = new Date(d.eventDateTime);
// you can remove this condition and initialize groupTime with [0].eventDateTime
if (!groupTime) groupTime = new Date(time.getTime() + 15 * 60000);
return time - groupTime <= 900000 ? groupTime : groupTime = time;
});
// modify the groupedData keys however u want
console.log(groupedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>
关于Javascript 按时间间隔对数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811564/