Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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?

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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'));

almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda