I have an array of start times and stop times for a stopwatch. I need to turn them into one final array that is the actual amount of time that passed for each entry. I always need the length of the final array to be 4, so if there are fewer than 4 times entries, I need a 0 to be in the final array in that place. The amount of input entries will always be 4 or less.
Example input:
[
{ startTime: 1234, stopTime: 2345 },
{ startTime: 3452, stopTime: 9304 },
{ startTime: 2345, stopTime: 7432 },
{ startTime: 4567, stopTime: 6252 }
]
Desired output:
[ 1111, 5852, 5087, 1685 ]
However, if there are fewer than 4 entries, I want them to be 0 instead.
Example Input:
[
{ startTime: 1234, stopTime: 2345 },
{ startTime: 3452, stopTime: 9304 }
]
Desired Output:
[ 1111, 5852, 0, 0 ]
Here is the code I currently have:
var times = [
{ startTime: 1234, stopTime: 2345 },
{ startTime: 3452, stopTime: 9304 }
]
function getTimes (arr) {
var output = arr.map(function (interval) {
return interval.stopTime - interval.startTime
})
return output
}
console.log(getTimes(times))
Right now, this doesn't do anything to make sure that the array is a length of 4 with the extra 0's added on. I know that one thing I could do is something like this:
while (output.length < 4) {
output.push(0)
}
But I was wondering if there was a better way to accomplish this rather than adding this after the map.