What is the elegant way to get the latest date from array of objects in client side?

后端 未结 9 1833
面向向阳花
面向向阳花 2020-11-27 06:17

I use angularjs in project.

I get array of objects from the server. Each object contains few properties and one of them is date property.

Here is the Array

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 07:10

    Also further to @TravisHeeter's answer..

    Instead of using 'filter' and grabbing the array index of [0], you can use the .find() method instead as follows:

    ....
    
    const mostRecentObject = a.find( e => { 
        const d = new Date( e.MeasureDate ); 
        return d.getTime() == mostRecentDate.getTime();
    });
    

    This also makes the code more performant, as it will stop looking after it has found the result, rather than filter which will iterate over all objects in the array.

提交回复
热议问题