Utilizing the array.reduce
method, this code calculates the time differences between start and stop as it traverses through the array.
However, this basic implementation does not factor in events or tasks, for instance.
let data = [
{
action: "start",
time: 100
},
{
action: "stop",
time: 150
},
{
action: "start",
time: 250
},
{
action: "stop",
time: 350
},
{
action: "start",
time: 400
}
];
let end = 450; // should be Date.now(),
let sum = data.reduce(function (r, a) {
return r + (a.action === 'start' ? -a.time : a.time);
}, data[data.length - 1].action === 'start' ? end : 0);
console.log(sum);
A potential scalable version of the data array could look like this:
let data = [
{
activity: "JOB",
event: "CLOCK IN",
task: "TRAVEL",
desc: "Job #12345",
time: 100
},
{
activity: "JOB",
event: "CLOCK IN",
task: "ON SITE",
desc: "Job #12345",
time: 150
},
{
activity: "JOB",
event: "CLOCK IN",
task: "BREAK",
desc: "Job #12345",
time: 250
},
{
activity: "JOB",
event: "CLOCK IN",
task: "ON SITE",
desc: "Job #12345",
time: 350
},
{
activity: "JOB",
event: "CLOCK OUT",
task: "HOME",
desc: "Job #12345",
time: 450
}
];
The process of learning Array.reduce has posed some challenges. Any guidance on how to approach it would be highly appreciated.
What modifications can be made to iterate through a scalable array using this code?