如何使用lodash查找具有最接近时间戳记的记录?

时间:2020-05-08 00:28:42

标签: typescript filter timestamp lodash

我是lodash的新手,想用它在包含最接近给定timestamp / 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处的时间戳记最接近)

我希望它在包含最接近的时间戳/ x值(将为5)的索引处返回记录的y值。返回整个记录也可以。我可以通过某种方式访问​​y值。

哪种lodash方法是实现此目标的理想方法,我将如何构建它?

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

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

非常感谢您的输入!

2 个答案:

答案 0 :(得分:0)

您可以使用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)

答案 1 :(得分:0)

您可以找到这样的时间戳。我认为时间戳记不是在同一天。

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);