我正在嘗試獲取最近的日期,即當前日期的下一個日期,但我不知道如何獲取。我試圖對預訂串列陣列進行排序,但它給了我上一個日期。
這是我的陣列:
const bookingsList = [
{
sitterName: 'John',
start: '2021-12-09',
end: '2021-12-09',
status: 'accepted',
},
{
sitterName: 'John',
start: '2021-12-06',
end: '2021-12-06',
status: 'accepted',
},
{
sitterName: 'John',
start: '2021-12-08',
end: '2021-12-08',
status: 'accepted',
},
{
sitterName: 'Guru',
start: '2021-11-30',
end: '2021-11-30',
status: 'accepted',
},
];
const sortedBookings = bookingsList.sort(sortFunction);
function sortFunction(a: any, b: any) {
const dateA = new Date(a.start).getTime();
const dateB = new Date(b.start).getTime();
return dateA > dateB ? 1 : -1;
}
console.log(sortedBookings[0].start);
uj5u.com熱心網友回復:
如果您對陣列進行了排序,則可以使用函式 find() 獲取與條件匹配的第一個元素。條件可以是 element.date > Date.now()。看一下代碼:
var found = sortedBookings.find((function (element) {
return new Date(element.start) > Date.now();
}));
uj5u.com熱心網友回復:
let sorted = bookingsList.sort((a,b) => Date.parse(a.start) - Date.parse(b.start));
let closestToRightNow = sorted.find(x => Date.parse(x.start) > Date.now()); // Date.now() is current time if you need something else use that
console.log(closestToRightNow.start);
uj5u.com熱心網友回復:
我可能會為此遇到麻煩..但這是一種方法。將今天的日期添加到陣列中,對其進行排序并選擇陣列中的下一項。然后洗掉陣列添加。這不是最好的解決方案,但會讓你到達你想去的地方。
const bookingsList = [{
sitterName: 'John',
start: '2021-12-09',
end: '2021-12-09',
status: 'accepted',
},
{
sitterName: 'John',
start: '2021-12-06',
end: '2021-12-06',
status: 'accepted',
},
{
sitterName: 'John',
start: '2021-12-08',
end: '2021-12-08',
status: 'accepted',
},
{
sitterName: 'Guru',
start: '2021-11-30',
end: '2021-11-30',
status: 'accepted',
},
];
let today = new Date()
today = today.getFullYear() "-" (today.getMonth() 1) "-" ("0" today.getDate()).slice(-2);
console.log('today', today);
// does it exist?
if (!bookingsList.find(a => a.start === today)) {
bookingsList.push({
sitterName: 'deleteme',
start: today
});
}
let sortedBookings = bookingsList.sort(sortFunction);
function sortFunction(a, b) {
const dateA = new Date(a.start).getTime();
const dateB = new Date(b.start).getTime();
return dateA > dateB ? 1 : -1;
}
let index = bookingsList.findIndex(a => a.start === today);
let target = sortedBookings[(index 1)]?.start;
console.log('next date', target);
// now remove the placeholder if there
sortedBookings = sortedBookings.filter(a => a.sitterName !== 'deleteme');
console.log('final array', sortedBookings)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370884.html
標籤:javascript 数组 反应 日期 类型
