2 回答
TA贡献1801条经验 获得超16个赞
按日期对数组进行排序并选择第一个和最后一个:
const dates = [
{ settledDate: "12-19-2018" },
{ settledDate: "12-12-2018" },
{ settledDate: "10-19-2018" },
{ settledDate: "10-12-2018" }
];
const sorted = dates.sort((a, b) => new Date(a.settledDate) - new Date(b.settledDate));
const minDate = sorted[0];
const maxDate = sorted.reverse()[0];
console.log('maxDate : ', maxDate.settledDate);
console.log('minDate : ', minDate.settledDate);
TA贡献1789条经验 获得超8个赞
这是一个线性时间O(n)解决方案。(我在链接的重复问题中没有找到任何线性时间解决方案。)
const dates = [
{ settledDate: "12-19-2018" },
{ settledDate: "12-12-2018" },
{ settledDate: "10-19-2018" },
{ settledDate: "10-12-2018" }
];
let maxDate = dates[0];
let minDate = dates[0];
dates.forEach(item => {
if (new Date(item.settledDate) < new Date(minDate.settledDate)) {
minDate = item;
}
if (new Date(item.settledDate) > new Date(minDate.settledDate)) {
maxDate = item;
}
});
console.log("minDate:", minDate);
console.log("maxDate:", maxDate);
添加回答
举报