I am working on a mileage application where I will need to summarize the miles driven by day and employee. I also need to determine the first trip taken each day by each employee. Here is the sample array that includes the date, employee, miles driven, and beginning odometer reading:
var records = [
["2019-08-26", emp1, 110, 45878],
["2019-08-26", emp2, 79, 21561],
["2019-09-02", emp1, 111, 46900],
["2019-09-02", emp2, 59, 21789],
["2019-09-02", emp3, 22, 95781],
["2019-09-05", emp3, 26, 95835],
["2019-09-02", emp1, 12, 46971],
["2019-09-05", emp3, 50, 95895],
["2019-09-02", emp2, 49, 21812],
["2019-09-05", emp1, 69, 47011],
["2019-09-02", emp1, 42, 46950],
["2019-09-05", emp3, 21, 95911],
["2019-09-02", emp2, 101, 22017],
["2019-09-05", emp3, 78, 96001],
["2019-09-02", emp3, 35, 95421],
["2019-09-05", emp1, 47, 47065]
]
I am trying to create an object with the following output.
[
{date: "2019-08-26", employee: emp1, miles: 111, firstTrip: 110},
{date: "2019-08-26", employee: emp2, miles: 79, firstTrip: 79},
{date: "2019-09-02", employee: emp1, miles: 65, firstTrip: 111},
{date: "2019-09-02", employee: emp2, miles: 209, firstTrip: 59},
{date: "2019-09-02", employee: emp3, miles: 57, firstTrip: 35},
etc
]
However, I can't seem to figure out how to identify the first distance traveled by analyzing the lowest odometer reading each day for each employee. Here is the using the reduce function that @Macarthurval helped me out with for everything but the "firstTrip":
var summary = records.reduce( function(total,record){
var index = -1;
total.forEach( function(s,i){
if( s.date == record[0] && s.employee == record[1] ) index = i;
});
if( index == -1 ){
total.push( {date: record[0], employee: record[1], miles: record[2]} );
}else{
total[ index ].miles += record[2];
total[ index ].firstTrip = record[3];
}
return total;
},[]);