[英]Get latest object with oldest date from array of objects with date object
[英]Get object from array with latest value in date property?
我想從date屬性中具有最新/最大值的數組中獲取對象。 有沒有很好的方法可以做到這一點?
[
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"Date": "2019-02-01T00:01:01.001Z",
"Value": -1
},
{
"Address": 26,
"AlertType": 1,
"Area": "West",
"Date": "2016-04-12T15:13:11.733Z",
"Value": -1
},
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"Date": "2017-02-01T00:01:01.001Z",
"Value": -1
}
.
.
.
]
使用Reduce(O(n)):
var data = [{ "Address": 25, "AlertType": 1, "Area": "North", "Date": "2019-02-01T00:01:01.001Z", "Value": -1 }, { "Address": 26, "AlertType": 1, "Area": "West", "Date": "2016-04-12T15:13:11.733Z", "Value": -1 }, { "Address": 25, "AlertType": 1, "Area": "North", "Date": "2017-02-01T00:01:01.001Z", "Value": -1 }] console.log( data.reduce((a,b)=>new Date(a.Date).getTime() > new Date(b.Date).getTime()? a : b, {}) )
排序(O(n log n)):
var data = [{ "Address": 25, "AlertType": 1, "Area": "North", "Date": "2019-02-01T00:01:01.001Z", "Value": -1 }, { "Address": 26, "AlertType": 1, "Area": "West", "Date": "2016-04-12T15:13:11.733Z", "Value": -1 }, { "Address": 25, "AlertType": 1, "Area": "North", "Date": "2017-02-01T00:01:01.001Z", "Value": -1 }] console.log( data.sort((a,b)=>new Date(b.Date).getTime() - new Date(a.Date).getTime())[0] )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.