我正在对数组进行映射以获取其最大值,然后执行indexOf以获取结果的索引:
var dates = [
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2019-02-01T00:01:01.001Z",
"MeasureValue": -1
},
{
"Address": 26,
"AlertType": 1,
"Area": "West",
"MeasureDate": "2023-04-12T15:13:11.733Z",
"MeasureValue": -1
},
{
"Address": 25,
"AlertType": 1,
"Area": "North",
"MeasureDate": "2017-02-01T00:01:01.001Z",
"MeasureValue": -1
}
]
这是我的尝试:
var result = dates
.map(x => x.MeasureDate)
.indexOf(new Date(Math.max(
...dates.map(a => new Date(a.MeasureDate))
)))
console.log('latest date', result)
但结果是
-1
。我如何解决它以获得正确的结果索引?
最佳答案
一种方法是使用findIndex函数并通过getTime比较日期
const getTime = value => new Date(value).getTime();
const result = dates.findIndex( item => getTime(item.MeasureDate) === Math.max(...dates.map( item => getTime(item.MeasureDate))))