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

93
Views
Cómo encontrar el índice del objeto en una matriz con la fecha más reciente

Tengo una matriz de objetos en una matriz. Cada objeto tiene un campo de fecha. Aquí hay un método que escribí para recuperar el índice del objeto con la fecha más reciente, funciona bien:

 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; }

¿Cómo se puede escribir esto (mucho) más sucintamente?

Gracias por cualquier ayuda.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Puedes hacerlo con un reduce , algo como:

 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

Puedes hacer esto usando una función incorporada como esta

 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)

Sin embargo, es menos eficiente, ya que necesita hacer múltiples pases a través de la matriz.

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!