In this lesson I am taking an array of elements with a data attribute of [data-time]. With that array I calculate the 'total' amount of time in 'hours', 'minutes' and 'secondsLeft'.
First to get the total 'seconds', .map() over each node to get the 'dataset.time'. Then .map() over each 'timeCode'.
.split(':') the string into a sub array of 'mins' and 'secs' (const [mins, secs] = timeCode.split(':').map(parseFloat)). Then return the total amount of 'seconds' for that item by counting all minutes and seconds as 'seconds' ((mins * 60) + secs).
Next .reduce() the array to get the total number of 'seconds' by adding up each items' 'seconds' (.reduce((total, vidSeconds) => total + vidSeconds). Then calculate 'hours', 'mins' and 'secondsLeft'.
let secondsLeft = seconds;
const hours = Math.floor(seconds / 3600);
secondsLeft = secondsLeft % 3600;
const mins = Math.floor(secondsLeft / 60);
secondsLeft = secondsLeft % 60;
Finally, output the values to the 'innerHTML' of 'total'.
See the Pen
JavaScript30 - 18 - Adding Up Times With Reduce by Corey Noble (@CoreyNoble)
on CodePen.