javascript - 以 5 分钟间隔对数组进行排序,并具有唯一值计数

标签 javascript typescript

我正在尝试以这样的方式对数组进行排序,以便获取从当天开始的 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/

相关文章:

javascript - View 和 View 模型连接

javascript - 如何解析 jQuery 中的 promise 链?

javascript - 如何通过循环正确使用生成器

javascript - 当类实例不可访问时,如何模拟类的特定方法,同时保持所有其他方法的实现?

javascript - 根据窗口高度添加CSS

javascript - 如何将日期数组传递给 react-dates 组件?

javascript - 将 NodeJs 导入 TypeScript 编译错误

reactjs - React hook useRef 不适用于样式组件和 typescript

css - 如何从一组颜色中动态地脉动文本颜色?

angular - 当用户在 Angular 2 的 View 中更改某些内容时如何检测组件的更改?