从数组中获取具有date属性中最新值的对象?

时间:2018-10-18 11:37:54

标签: javascript arrays

我想从date属性中具有最新/最大值的数组中获取对象。有什么好方法吗?

/usr/lib/jvm/java-8-openjdk-amd64/bin/java -jar target/app.jar

1 个答案:

答案 0 :(得分:2)

使用减少(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]
)