I am trying to filter an array of objected based on the vch_number is not duplicate & if it is duplicate only return the highest of the lastChecked value.
I have tried filter with indexOf however, indexof only returns the first index only.
Also tried to do it with Set but I couldn't get it to work either.
below is the array
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"
}
}
]
I am trying to add to this below function
const filters = ()=>{
const obj = {
}
for (let i of car){
obj[i.vch_number]= i
}
console.log(obj)
}
filters()
I tried the following & not sure what I am missing
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)