Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!