gpt4 book ai didi

javascript - 如何找到数组对象中的近距离,并选择近距离并提取对象

转载 作者:行者123 更新时间:2023-12-02 23:30:53 25 4
gpt4 key购买 nike

我试图在数据集数组中找到最接近的具有起点和终点的对象。

    startTime = 1559923201;
endTime = 1560009601;
DataSet = [
{"time":1549923201,"value":12},
{"time":1559923200,"value":10},
{"time":1559923000,"value":5},
{"time":1560058490,"value":4},
{"time":1560058800,"value":3},
{"time":1560059500,"value":2}];

我可以找到最接近的,如何找到数组的索引。

var start = DataSet.reduce(function(prev,curr) {
return (Math.abs(curr["time"] - startTime) < Math.abs(prev["time"] - startTime) ? curr : prev);
});

var end = DataSet.reduce(function(prev,curr) {
return (Math.abs(curr["time"] - endTime) < Math.abs(prev["time"] - endTime) ? curr : prev);
});




我正在寻找的结果与数据集非常接近,如下所示:

    ResultSet  = [
{"time":1559923200,"value":10},
{"time":1559923000,"value":5}];

提前致谢。

最佳答案

您可以过滤数据集并通过一些r调整可接受的时间范围:

const r = 500 // half a second either side of start time
DataSet.filter(d => (d.time >= startTime-r) && (d.time <= endTime+r))

返回:

[
{"time":1559923200,"value":10},
{"time":1559923000,"value":5}
]

关于javascript - 如何找到数组对象中的近距离,并选择近距离并提取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56513646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com