如何在数组中查找具有最新日期的对象的索引



我在一个数组中有一个对象数组。每个对象都有一个日期字段。以下是我编写的一种方法,用于检索具有最新日期的对象的索引,效果良好:

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

这怎么能写得更简洁呢?

谢谢你的帮助。

我建议使用javascript提供的reduce函数。该解决方案也不会在数组中循环多次,并且它在每个日期调用new Date().getTime()一次。

GetIndexOfLatestDate()
{
if (this.objectArr === null || this.objectArr.length === 0) {
return null;
}
return this.objectArr.reduce((accum, value, index) => {
const newDate = new Date(value.date).getTime();
return newDate > accum.maxDate ? {index, maxDate: newDate} : accum;
}, {index: 0, maxDate: new Date(this.objectArr[0].date).getTime()}).index;
}

如果这看起来太令人困惑,这里有一个扩展版本,如果你是reduce函数的新手,它更容易遵循。

GetIndexOfLatestDate()
{
// check if object arr is empty
if (this.objectArr === null || this.objectArr.length === 0) {
return null;
}
// set default accumulator for first passthrough
const defaultAccum = {  
index: 0, 
maxDate: new Date(this.objectArr[0].date).getTime()
}
const maxValueWithIndex = this.objectArr.reduce((accum, value, index) => {
// set formatted date to prevent multiple Date() calls
const newDate = new Date(value.date).getTime();
// if the new date is larger than the current largest date, set
// the accumulator to the new largest date and its index
if (newDate > accum.maxDate)
accum = {
index: index, 
maxDate: newDate
};
} 

// return the current accumulator, i.e. the current largest date
return accum;
}, defaultAccum);
// return the index of the latest date
return maxValueWithIndex.index;
}

您可以使用像这样的内置函数来实现这一点

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)

不过,它的效率较低,因为它需要多次通过阵列

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));
GetIndexOfLatestDate(objArray){
let max = objArray.reduce(function (a, b){ return new Date(a.date) > new 
Date(b.date) ? a : b; });
return objArray.indexOf(max);
}

您可以使用reduce,类似于:

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;

最新更新