【发布时间】:2021-03-20 21:40:07
【问题描述】:
我正在尝试根据 vch_number 不重复过滤一个对象数组,如果重复,则仅返回 lastChecked 值的最高值。
我试过用 indexOf 过滤,但是 indexof 只返回第一个索引。
也尝试用 Set 来做,但我也无法让它工作。
下面是数组
const car = [
{
"status": "available",
"lastChecked": 1,
"make": "bwm",
"model": "i8",
"year": 2000,
"vch_number": 51511,
"description": "fully loaded",
"VehcileStatusReport": {
"statusId": 1,
"description": null,
"createdAt": "2021-03-16T02:02:15.000Z",
"updatedAt": "2021-03-16T02:02:15.000Z"
}
},
{
"status": "parked",
"lastChecked": 2,
"make": "bwm",
"model": "i8",
"year": 2000,
"vch_number": 51510,
"description": "fully loaded",
"VehcileStatusReport": {
"statusId": 1,
"description": null,
"createdAt": "2021-03-16T01:39:48.000Z",
"updatedAt": "2021-03-16T01:39:48.000Z"
}
},
{
"status": "service",
"lastChecked": 3,
"make": "bwm",
"model": "i8",
"year": 2000,
"vch_number": 51510,
"description": "fully loaded",
"VehcileStatusReport": {
"statusId": 1,
"description": null,
"createdAt": "2021-03-16T01:39:48.000Z",
"updatedAt": "2021-03-16T01:39:48.000Z"
}
}
]
我正在尝试添加到下面的函数中
const filters = ()=>{
const obj = {
}
for (let i of car){
obj[i.vch_number]= i
}
console.log(obj)
}
filters()
我尝试了以下但不确定我错过了什么
const newVchs = car.reduce((acc, current)=>{
const x = acc.find(item => item.vch_number === current.vch_number && item.lastChecked > current.lastChecked)
if(!x){
return acc.concat([current])
}else{
return acc
}
return acc
},[])
console.log(newVchs)
【问题讨论】:
标签: javascript arrays object higher-order-functions