简体   繁体   English

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

[英]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.每个 object 都有一个日期字段。 Here is a method I wrote to retrieve the index of the object with the newest date, works fine:这是我编写的一种方法,用于检索具有最新日期的 object 的索引,工作正常:

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.谢谢你的帮助。

You can do it with a reduce , something like:您可以使用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;

You can do this using built-in function like this您可以像这样使用内置的 function 来执行此操作

 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但是效率较低,因为它需要多次遍历数组

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

I would suggest using the reduce function that javascript provides.我建议使用 javascript 提供的reduce function。 This solution also doesn't loop through the array multiple times, and it calls new Date().getTime() once per date.该解决方案也不会多次循环遍历数组,并且每个日期调用一次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;
}

if this looks too confusing, here is an expanded version that's easier to follow if you are new to the reduce function.如果这看起来太令人困惑,这里有一个扩展版本,如果您是 reduce 的新手,它更容易理解 function。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM