如何获取对象数组中时间最早的元素?
获取数组中时间最早的元素
给定如下对象数组:
const sessions = [ {videoStartTime: "2022-08-23T12:05:28.000Z"}, {videoStartTime: "2022-08-23T11:39:51.000Z"}, {videoStartTime: "2022-08-23T10:51:03.000Z"}, {videoStartTime: "2022-08-22T15:49:44.000Z"}, {videoStartTime: "2022-08-22T15:34:42.000Z"}, {videoStartTime: "2022-08-22T15:25:58.000Z"}, {videoStartTime: "2022-08-17T11:11:05.000Z"} ]
需要编写函数找出数组中时间最早的元素,期望输出为:{videoStartTime: "2022-08-17T11:11:05.000Z"}
解决方案
直接使用数组的reduce()方法就能实现,因为这里的时间是ISO 8601格式的字符串,这种格式的字符串可直接按字典序比较,结果和时间先后顺序完全一致,无需额外转成Date对象。
代码示例:
function getEarliestSession(sessions) { if (!sessions.length) return null; // 空数组时返回null,可按需调整返回值 return sessions.reduce((earliest, current) => { return current.videoStartTime < earliest.videoStartTime ? current : earliest; }); } // 调用函数 const earliestSession = getEarliestSession(sessions); console.log(earliestSession); // 输出:{videoStartTime: "2022-08-17T11:11:05.000Z"}
额外说明
- 如果数组可能为空,记得处理这种边界情况,上述代码返回
null,你可以根据需求改成返回空对象或其他默认值。 - 若时间格式不是ISO 8601,需要先将字符串转为
Date对象再比较,比如new Date(current.videoStartTime) < new Date(earliest.videoStartTime),这种方式兼容性没问题,但性能会稍差一点。
内容的提问来源于stack exchange,提问作者fadsgas
相关产品推荐
相关产品推荐

