我正在尝试使用起点和终点在 DataSet Array 中找到最近的对象。 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);}); 我正在寻找的结果是,距离 DataSet 非常近,例如: ResultSet = [ {"time":1559923200,"value":10}, {"time":1559923000,"value":5}];提前致谢。
1 回答
千巷猫影
TA贡献1829条经验 获得超7个赞
您可以过滤数据集并通过一些调整可接受的时间范围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}
]
添加回答
举报
0/150
提交
取消