【问题标题】:Sorting and Mapping Array by time and amount of values按时间和值的数量对数组进行排序和映射
【发布时间】:2020-10-15 11:42:41
【问题描述】:

我有一个对象数组的以下输入:

[
  {
    timestamp: 1602754921328,
    product: "productA"
  }, 
  {
    timestamp: 1602754921942,
    product: "productB"
  },
  {
    timestamp: 1602754924160,
    product: "productA"
  },
  {
    timestamp: 1602757547704,
    product: "productB"
  },
  {
    timestamp: 1602757563480,
    product: "productC"
  },
  {
    timestamp: 1602757567032,
    product: "productB"
  }
]

其中时间戳是一个 unix 时间戳,乘积是任何字符串值。 输入数组包含从一天开始到一天结束的值,即 24 小时。

我们的目标是将这些值分成 4 小时的段,即 6 个不同的段,并在这些段中填充该值在 4 小时内出现在数组中的次数。

预期的输出是:

[
  {
    name: "productA",
    data: [0, 0, 2, 0, 0, 0]
  },
  {
    name: "productB",
    data: [0, 0, 1, 2, 0, 0]
  },
  {
    name: "productC",
    data: [0, 0, 0, 1, 0, 0]
  },
]

输出包含在输入数组中找到的每个值,其中包含 6 个值的数组(我们称之为数据),其中每个值是在数组中找到该值的次数特定的 4 小时时段。

我已设法将输入数据拆分为 6 个数组,这些数组对应于各个 4 小时的时间段,但我不确定这是否是第一步的正确方法,并且我在从这一步到需要的时候遇到了麻烦输出。

感谢任何方向,我正在使用javascript编写函数。

【问题讨论】:

    标签: javascript arrays sorting timestamp mapping


    【解决方案1】:

    您可以与产品进行分组,并获得一个索引来计算时间戳的某个插槽。

    const
        data = [{ timestamp: 1602754921328, product: "productA" }, { timestamp: 1602754921942, product: "productB" }, { timestamp: 1602754924160, product: "productA" }, { timestamp: 1602757547704, product: "productB" }, { timestamp: 1602757563480, product: "productC" }, { timestamp: 1602757567032, product: "productB" }],
        getIndex = t => Math.floor(Math.floor(t / 1000 / 60 / 60) % 24 / 4),
        result = Object.values(data.reduce((r, { timestamp, product: name }) => {
            if (!r[name]) r[name] = { name, data: Array(6).fill(0) };
            r[name].data[getIndex(timestamp)]++;
            return r;
        }, {}));
          
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2019-03-13
      • 2021-12-15
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2018-01-15
      相关资源
      最近更新 更多