我正在尝试以这样的方式对数组进行排序,以便获取从当天开始的 0:00 开始的 5 分钟间隔内唯一用户的计数。 如何定义纪元时间中的 5 分钟间隔? (使用的数据将是当天的纪元)以及如何获取该时间间隔的唯一用户计数?
输入
[1486428994000, "user a"]
[1486429834000, "user a"]
[1486429839000, "user a"]
[1486429869000, "user b"]
所需输出
[1486428900000, 1 ]
[1486429800000, 2 ]
最佳答案
// Remove doublons from an array.
const uniq = array =>
array.filter((value, index) => array.indexOf(value) === index);
// Your function.
const groupCount = (data, timeWindow) =>
data
.reduce((groups, line) => {
const current = groups[groups.length - 1];
// If the line is outside of the current time window, push a new group.
if (!current || line[0] > current[0] + timeWindow) {
// Find the beginning of the corresponding time window.
const windowStart = line[0] - line[0] % timeWindow;
// Push the new group.
groups.push([windowStart, [line[1]]]);
} else {
// Else add a new user to the group.
current[1].push(line[1]);
}
return groups;
}, [])
// Once we created the groups, we remove doublons from them and count users.
.map(group => [group[0], uniq(group[1]).length]);
const data = [
[1486428994000, "user a"],
[1486429834000, "user a"],
[1486429839000, "user a"],
[1486429869000, "user b"]
];
console.log(groupCount(data, 5 * 60 * 1000));
关于javascript - 以 5 分钟间隔对数组进行排序,并具有唯一值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44525034/