I have a simple, unsorted array of objects:
const items = [
{ item: 'Two', date: '2018-01-01' },
{ item: 'Three', date: '2019-01-01' },
{ item: 'One', date: '2022-01-01' },
{ item: 'Four', date: '2021-01-01' },
];
I am trying to build a function that takes a single effDate parameter and returns the most recent item whose date property is prior to the effDate.
For example, if I pass 2020-08-22 as the parameter, the function would return item Three, since it is the closest to the effDate without going over.
I have tried to use a reducer, but I am sure I am doing this wrong, since it always returns the first object in the array:
const getItem = (effDate) => {
return items.reduce((prev, next) => {
return next.date > prev.date && next.date < effDate.date
? next
: prev;
});
};
So, without building an entire looping / comparison function myself, is this possible with the built-in JS tools?