I have a list of rescues for ambulance drivers in different states that are displayed on a kanban board. My JSON object is divided by the status of the rescues, and then grouped by driver. The structure is like this:
--Status (unassigned/assigned/arrived/rescued)
----Driver group
-------Rescue list
The rescues have a datetime and lat/long associated with them, so I can use map/reduce to find the rescue that the drivers attended most recently, and show that location on a map.
One issue is that a driver group can exist in one swimlane and none of the other.
I want to: filter the list down to the arrived/rescued states only, (although logically this may not be necessary as it's not possible to have an arrival time without a driver associated, but this is out of scope) and for each driver group return their latest rescue by arrival time or rescue time. This will leave me with a distinct list of driver groups, with only the most recent rescue for that group
Here's the working code:
let groups = cases
.filter(swimlane => parseInt(swimlane.rescueStatus) >= 3)
.map(groups => groups.rescuerGroups)
.map(rescuerGroups => rescuerGroups)
.reduce((result, current) => {
if(result.length === 0){
return current;
}
else{
current.forEach(currentRescueGroup => {
let index = result.findIndex(parentRescueGroup => {
return parseInt(parentRescueGroup.rescuer1) == parseInt(currentRescueGroup.rescuer1) &&
parseInt(parentRescueGroup.rescuer2) == parseInt(currentRescueGroup.rescuer2)
})
index > -1 ?
result[index].rescues = result[index].rescues.concat(currentRescueGroup.rescues)
:
result.push(currentRescueGroup);
})
return result;
}}, [])
.map(rescueGroup => {
let maxRescue = rescueGroup.rescues.reduce((current, previous) => {
let currentTime = new Date(current.ambulanceArrivalTime) > (new Date(current.rescueTime) || new Date(1901, 01, 01)) ? current.ambulanceArrivalTime : current.rescueTime;
let previousTime = new Date(previous.ambulanceArrivalTime) > (new Date(previous.rescueTime) || new Date(1901, 01, 01)) ? previous.ambulanceArrivalTime : previous.rescueTime;
return previousTime > currentTime ? current : previous;
})
return {
rescuer1Abbreviation: rescueGroup.rescuer1Abbreviation,
rescuer2Abbreviation: rescueGroup.rescuer2Abbreviation,
latestLocation: maxRescue.latLngLiteral,
rescues: rescueGroup.rescues
}
})
And here's a JSBin including the working code:
https://jsbin.com/hocasob/edit?js,console
Any help to make the reduce sections simpler would be much appreciated
parseIntrequires a radix (it does not default to10). Another option would be to use theNumberconstructor instead. Also you could extract the accumulators outside as a variable and use argument destructuring. \$\endgroup\$