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