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

91
Vistas
How to find index of object in array with latest date

I have an array of objects in an array. Each object has a date field. Here is a method I wrote to retrieve the index of the object with the newest date, works fine:

GetIndexOfLatestDate()
   {
    var indexOfLatestDate:number = 0;
    
    var maxDate:number = new Date(this.objArray[0].date).getTime();
    
    for(var nIndex:number = 1; nIndex < this.m_objArray.length; nIndex++)
    {
      if(new Date(this.objArray[nIndex].date).getTime() > maxDate)
      {
        maxDate = new Date(this.objArray[nIndex].date).getTime();
        indexOFLatestDate = nIndex;
      }
    }

    return indexOfLatestDate;
   }

How can this be written (much) more succinctly?

Thanks for any help.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can do it with a reduce, something like:

index = this.objArray.reduce((accum, value, index) => {
   if(!accum){
      accum = {
          index,
          maxDate: value.date
      };
   } else {
      if(accum.maxDate.getTime() > value.date.getTime()){
          accum = {
              index,
              maxDate: value.date
          };
      }
   }

   return accum;
}

}, null).index;
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do this using built-in function like this

const array1 = [{date: '2/5/2021'}, {date: '3/11/2019'}, {date: '12/9/2022'}];

const dateArray = array1.map(({date}) => {return new Date(date)})
const maxDate = Math.max(...dateArray);
const indexMaxElem = dateArray.findIndex(dateObj => dateObj.getTime() === maxDate)
console.log(indexMaxElem)

It is less efficient though, since it needs to do multiple pass through the array

about 4 years ago · Juan Pablo Isaza Denunciar

0

let dateArr = [];
objArray.forEach(item => {

    //  extract the dates from the source array to form new array
    dateArr.push(objArray.date.getTime();
});

// find the maximum date in this array, which will have the same index
indexOfLatest = dateArr.findIndex(Math.max(...dateArr));
about 4 years ago · Juan Pablo Isaza 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