How can I find out the min and the max date from an object? Currently, I am getting an array like this: min date should be ‘2010-02-24’ and max date should be ‘2022-10-04’.
Is there any built-in function to do this? Thanks in advance.
{
"2010":[
{
"id":1243,
"eventName":"sample_01",
"categoryType":"CUSTOM_NOTES",
"tags":"tag19",
"startDate":"2010-02-24",
"endDate":"2010-02-26",
"attachments":[
]
}
],
"2022":[
{
"id":1244,
"eventName":"sample_02",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12, tag3, tag52, tag19",
"startDate":"2022-10-04",
"endDate":"2022-12-12",
"attachments":[
]
},
{
"id":1245,
"eventName":"hello_03",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12",
"startDate":"2022-06-01",
"endDate":"2010-06-26",
"attachments":[
]
}
]
}
filterEventsByDates = () => {
const filterDateFn = (a, b) => a.startDate.localeCompare(b.startDate);
setDateFiltersToState(filterDateFn);
}
setDateFiltersToState = (filterDateFn) => {
this.setState(state => {
const events = {};
for (const [year, items] of Object.entries(state.events)) {
events[year] = items.slice().filter(filterDateFn);
}
return { events };
});
}
Advertisement
Answer
A sort will do the job here, by packing all dates into an array first:
const values = {
"2010":[
{
"id":1243,
"eventName":"sample_01",
"categoryType":"CUSTOM_NOTES",
"tags":"tag19",
"startDate":"2010-02-24",
"endDate":"2010-02-26",
"attachments":[
]
}
],
"2022":[
{
"id":1244,
"eventName":"sample_02",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12, tag3, tag52, tag19",
"startDate":"2022-10-04",
"endDate":"2022-12-12",
"attachments":[
]
},
{
"id":1245,
"eventName":"hello_03",
"categoryType":"CUSTOM_NOTES",
"tags":"tag1, tag12",
"startDate":"2022-06-01",
"endDate":"2010-06-26",
"attachments":[
]
}
]
};
// include startDate only
const dates = Object.values(values).flatMap(v =>
v.map(({startDate}) => startDate)).sort();
console.log(dates[0], dates.pop());
// include startDate and endDate
const datesAny = Object.values(values).flatMap(v =>
v.flatMap(({startDate, endDate}) => [startDate, endDate])).sort();
console.log(datesAny[0], datesAny.pop());