我有一个排序数组:
[new Date('2017-01-02'), new Date('2017-01-07'), new Date('2017-01-09'), new Date('2017-01-17')]
现在我想找到任意两个相邻元素之间数组中出现的最小时间差。例如,在这种情况下:
new Date('2017-01-09').getTime() - new Date('2017-01-07').getTime()
是否有一些优雅的方式与地图或类似的东西或我必须循环,记住到目前为止的小间隔,然后更换值,如果更小的一个?
目前的解决方案:
let timestamps = Gps.find().map(doc => doc.timestamp);
timestamps.sort();
let minimumDifference;
let previousTimestamp;
timestamps.forEach(timestamp => {
if(!previousTimestamp) {
previousTimestamp = timestamp;
}
else{
let difference = timestamp.getTime() - previousTimestamp.getTime();
if(!minimumDifference || minimumDifference > difference){
minimumDifference = difference;
}
previousTimestamp = timestamp;
}
});
答案 0 :(得分:0)
我想回到过去的日子。普通的旧javascript。没有创建不必要的副本
var timestamps = [1,2,5,9];
timestamps.sort();
var result = timestamps[timestamps.length-1];
for(var i=1;i<timestamps.length;i++){
result = (timestamps[i]-timestamps[i-1])<result?(timestamps[i]-timestamps[i-1]):result;
}
采取工厂并以同样的方式进行