【问题标题】:How can I use lodash to find the record with the closest timestamp?如何使用 lodash 查找时间戳最近的记录?
【发布时间】:2026-02-20 22:55:01
【问题描述】:

我是 lodash 的新手,想用它来查找数据集中包含最接近给定时间戳/x 值的时间戳的对象的索引。

假设我的时间戳为var timestamp = "2019-01-01 01:01:30"

我的数据集如下所示:

dataset = [{
    x: "2019-01-01 00:01:38",
    y: 1
  },
  {
    x: "2019-01-01 01:01:39",
    y: 5
  },
  {
    x: "2019-01-01 02:01:40",
    y: 4
  },
  {
    x: "2019-01-01 03:01:41",
    y: 1
  }
]

我希望它返回给我:包含最近时间戳的数据集的索引(在本例中为 1,因为索引 1 处的时间戳最接近)

我希望它返回索引处记录的 y 值,该索引包含最接近的时间戳/x 值(即 5)。返回整个记录也可以。只是我访问 y 值的某种方式。

哪种 lodash 方法最适合实现这一目标,我将如何构建它?

也许是使用 .filter 或 .find 的东西?

_.find(dataset, function(item) {
  return ...?
  );
})

非常感谢您的意见!

【问题讨论】:

    标签: typescript filter timestamp lodash


    【解决方案1】:

    你可以像这样找到时间戳。我假设时间戳不在同一天。

    const currentDate = new Date('2019-01-01 01:01:30');
    const currentSeconds = (currentDate.getHours() * 60) + (currentDate.getMinutes() * 60) + currentDate.getSeconds();
    const dates = _.map(dataset, set => {
        const date = new Date(set.x);
        if (date.getDate === currentDate.getDate && date.getMonth === currentDate.getMonth && date.getFullYear === date.getFullYear) {
            const setInSeconds = (date.getHours() * 60) + (date.getMinutes() * 60) + date.getSeconds();
    
            return {
                x: set.x,
                y: set.y,
                difference: Math.abs(setInSeconds - currentSeconds)
            };
        }
    });
    const closestDate = _.minBy(dates, 'difference');
    console.log(closestDate);
    

    【讨论】:

      【解决方案2】:

      您可以使用Array.reduce() 或lodash 的_.reduce() 来迭代数组,并找出xtimestamp 之间的区别。存储差异和y 值(如果它较低)。对结果进行解构得到y 值。

      通过获取解析值之间差异的绝对值来计算diff

      const timestamp = "2019-01-01 01:01:30"
      
      const dataset = [{"x":"2019-01-01 00:01:38","y":1},{"x":"2019-01-01 01:01:39","y":5},{"x":"2019-01-01 02:01:40","y":4},{"x":"2019-01-01 03:01:41","y":1}]
      
      const [y] = dataset.reduce((r, { x, y }) => {
        const diff = Math.abs(Date.parse(timestamp) - Date.parse(x))
      
        return diff < r[1] ? [y, diff] : r
      }, [null, Infinity])
      
      console.log(y)

      【讨论】:

      • 有趣!在这种情况下,'r'基本上是代表记录还是索引?
      • 累加器。阅读一些关于 reduce 的内容。
      最近更新 更多