I would like to remove a date from an object than is lower than today's date: e.g. Today is: 2022-08-17
and I got { date: "2022-08-15" },
in my array of objects.
let todayDate = new Date().toISOString().slice(0, 10);
let arr = [
{ date: "2022-08-15" }, // todayDate is 2022-08-17 and this object should be removed
{ date: "2022-08-31" },
{ date: "2022-10-19" },
{ date: "2022-10-27" },
];
// result after filter
// let arr = [
// { date: "2022-08-31" },
// { date: "2022-10-19" },
// { date: "2022-10-27" },
CodePudding user response:
Parse the date with the Date
constructor, then check whether it is greater than the current date:
let arr = [
{ date: "2022-08-15" },
{ date: "2022-08-31" },
{ date: "2022-10-19" },
{ date: "2022-10-27" },
];
const now = Date.now()
const result = arr.filter(e => new Date(e.date) > now)
console.log(result)
Alternatively, you could compare the strings lexographically:
let todayDate = new Date().toISOString().slice(0, 10);
let arr = [
{ date: "2022-08-15" },
{ date: "2022-08-31" },
{ date: "2022-10-19" },
{ date: "2022-10-27" },
];
const result = arr.filter(e => e.date > todayDate)
console.log(result)