Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda