javascript - 如何使用矩在数组中获得最近的下一次?
问题描述
我想找到最接近给定时间的下一次,我从堆栈溢出中得到了这段代码,但我无法得到想要的结果
// Current time in millis
const now = +moment('10:07', 'HH:mm').format('x');
// List of times
const times = ["10:00", "10:18", "23:30", "12:00"];
// Times in milliseconds
const timesInMillis = times.map(t => +moment(t, "HH:mm").format("x"));
function closestTime(arr, time) {
return arr.reduce(function(prev, curr) {
return Math.abs(curr - time) < Math.abs(prev - time) ? curr : prev;
});
}
const closest = moment(closestTime(timesInMillis, now)).format('HH:mm');
// closest is 10:00 but i want the next time 10:18
console.log(closest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
解决方案
完全不需要片刻
24小时时间可排序,可直接比较
const times = ["10:00", "10:18", "23:30", "12:00"].sort();
const getClosest = targetTime => times.find(time => time >= targetTime) || "N/A";
console.log(getClosest("10:07"));
console.log(getClosest("11:30"));
console.log(getClosest("13:30"));
console.log(getClosest("23:40")); // not available in array
推荐阅读
- kendo-ui - 剑道上传。如何设置所需的输入?
- regex - 匹配指定长度字符串的正则表达式
- java - NoSuchMethodError - WebDriverWait / Wait.until(Ljava/util/function/Function;)
- android - MPAndroidChart - ViewPager 中的线图水平滚动 - Android
- mysql - Contains 与 ST_Contains Mysql 之间的区别
- webhooks - 带有事件订阅的 Webhook 传入创建循环
- database - 如何使用 MS SQL 仅查找带括号的字符串的最后一部分
- javascript - React:为什么在调用 setState 之前尝试以不可变的方式更改状态时会更改状态
- php - 如何从数组中获取数据?
- ios - 无法将模块“swiftyjson”加载为“SwiftyJSON”