I'm currently working on a task that involves filtering an array of objects to find the ones closest to today. Unfortunately, I encountered an issue where the code is returning dates in June instead of May. Here's the snippet of code I've been using:
const findClosest = (data, accessor, target = Date.now()) =>
data.reduce((prev, curr) => {
const a = Math.abs(accessor(curr).getTime() - target);
const b = Math.abs(accessor(prev).getTime() - target);
return a - b < 0 ? curr : prev;
});
const getClosestFromDate = (array, key, date) => {
let arr = array.filter((e) => e[key] == date);
return arr;
};
const sampleData = [{
"max_retries_reached": 0,
"next_charge_scheduled_at": "2022-06-23T00:00:00",
},
// additional object data here...
];
const processDateString = (dateString) => {
let date = new Date(dateString);
let year = date.getFullYear();
let month = date.getMonth();
console.log(date.toString());
return new Date(year, month + 1, date);
};
const closest = findClosest(sampleData, ({
next_charge_scheduled_at
}) => processDateString(next_charge_scheduled_at), "2022-05-10T03:03:42");
console.log(closest.next_charge_scheduled_at);
console.log(getClosestFromDate(sampleData, "next_charge_scheduled_at", closest.next_charge_scheduled_at));
I came across this piece of code while looking at solutions for similar questions. Despite my attempts to adjust the month variable, I haven't been able to retrieve the correct date. Any assistance you can offer would be greatly appreciated.