如何计算出现的次数并分配到合适的地方?
How to calculate the number of occurrences and assign them to the appropriate place?
我有如下纪元中的一组时间:
const times = [1653931370, 1653924170, 1653920570, 1653913370, 1653913370, 1653902570]
所有这些日期都来自 00:00 和 23:59 之间的一天。现在我需要将这些时间中的每一个分配给一个特定的小时以及该小时的出现次数。我的回复应该如下所示:
[
{
hour: 0, //00:00
occurs: 4
},
{
hour: 1, //01:00
occurs: 4
},
...
{
hour: 22, //22:00
occurs: 17
},
{
hour: 23, //23:00
occurs: 12
},
]
有人可以帮我解决这个问题吗?感谢您的帮助!
创建新对象。遍历所有 times
,例如 for each。使用 Date
class 像这样 new Date(epoch * 1000).getHours()
并存储那个时间。检查新对象上是否存在键 your_hour
。如果没有,就按 myResult[your_hour] = {hour: your_hour, occurances: 1}
这样的方式推送。如果它确实存在,则像这样 myResult[your_hour].occurances = myResult[your_hour].occurances + 1;
添加到该对象。这通常是我使用的方法,但对此有多种解决方案。
映射数组并使用 Date.prototype.getHours 方法获取小时数。
然后使用 Array.prototype.reduce.
对时间进行分组
const times = [
1653931370, 1653924170, 1653920570, 1653913370, 1653913370, 1653902570,
];
const res = Object.values(
times
.map((t) => new Date(t * 1000).getHours())
.reduce((r, t) => {
r[t] ??= { hour: t, occurs: 1 };
r[t].occurs += 1;
return r;
}, {})
);
console.log(res);
其他相关文件:
我有如下纪元中的一组时间:
const times = [1653931370, 1653924170, 1653920570, 1653913370, 1653913370, 1653902570]
所有这些日期都来自 00:00 和 23:59 之间的一天。现在我需要将这些时间中的每一个分配给一个特定的小时以及该小时的出现次数。我的回复应该如下所示:
[
{
hour: 0, //00:00
occurs: 4
},
{
hour: 1, //01:00
occurs: 4
},
...
{
hour: 22, //22:00
occurs: 17
},
{
hour: 23, //23:00
occurs: 12
},
]
有人可以帮我解决这个问题吗?感谢您的帮助!
创建新对象。遍历所有 times
,例如 for each。使用 Date
class 像这样 new Date(epoch * 1000).getHours()
并存储那个时间。检查新对象上是否存在键 your_hour
。如果没有,就按 myResult[your_hour] = {hour: your_hour, occurances: 1}
这样的方式推送。如果它确实存在,则像这样 myResult[your_hour].occurances = myResult[your_hour].occurances + 1;
添加到该对象。这通常是我使用的方法,但对此有多种解决方案。
映射数组并使用 Date.prototype.getHours 方法获取小时数。
然后使用 Array.prototype.reduce.
对时间进行分组
const times = [
1653931370, 1653924170, 1653920570, 1653913370, 1653913370, 1653902570,
];
const res = Object.values(
times
.map((t) => new Date(t * 1000).getHours())
.reduce((r, t) => {
r[t] ??= { hour: t, occurs: 1 };
r[t].occurs += 1;
return r;
}, {})
);
console.log(res);
其他相关文件: