How to retrieve the most recent object in an array prior to a given date?

Viewed 19

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?

1 Answers

As @Barmar said in comments:

Sort the array in reverse by date. Then use find() to find the first element before effData.

  1. sort date in descending order
  2. find the nearest to the date effDate

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' }, ];
const getItem = (effDate) => {
  //1.
  let itemsSorted = items.slice().sort((a, b) => Date.parse(b.date) - Date.parse(a.date))
  //2. 
  return itemsSorted.find(item => Date.parse(item.date) < Date.parse(effDate));
};
console.log(getItem('2020-08-22'));

Related