[英]Get object from array with latest value in date property?
I want to get the object from an array that has the latest/largest value in the date property. 我想从date属性中具有最新/最大值的数组中获取对象。 Is there a nice way to do this?
有没有很好的方法可以做到这一点?
[
{
"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
}
.
.
.
]
Using Reduce (O(n)): 使用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, {}) )
Sorting (O(n log n)): 排序(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.