- Published on
Day18: Adding Up Times with Reduce
- Authors

- Name
- irisjustdoit
- @irisjustdoit
Introduction: How to use JavaScript reduce method to calculate total video duration.
Project Page: https://iris1114.github.io/javascript30/18_Adding-Up-Times-with-Reduce/
HTML
- Contains a
ullist with multiplelielements, each having adata-timeattribute representing video duration
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Videos</title>
</head>
<body>
<ul class="videos">
<li data-time="5:43">Video 1</li>
<li data-time="2:33">Video 2</li>
<li data-time="3:45">Video 3</li>
<li data-time="0:47">Video 4</li>
<li data-time="5:21">Video 5</li>
<li data-time="6:56">Video 6</li>
<li data-time="3:46">Video 7</li>
<li data-time="5:25">Video 8</li>
<li data-time="3:14">Video 9</li>
</ul>
</body>
</html>
JavaScript
- Calculates total duration of all videos and displays result in console
const timeNodes = Array.from(document.querySelectorAll('[data-time]'))
const seconds = timeNodes
.map((node) => node.dataset.time)
.map((timeCode) => {
const [mins, secs] = timeCode.split(':').map(parseFloat)
return mins * 60 + secs
})
.reduce((total, vidSeconds) => total + vidSeconds)
let secondsLeft = seconds
const hours = Math.floor(secondsLeft / 3600)
secondsLeft = secondsLeft % 3600
const mins = Math.floor(secondsLeft / 60)
secondsLeft = secondsLeft % 60
console.log(hours, mins, secondsLeft)
Note
- Uses
Array.fromto convert NodeList to array - Uses
mapmethod to convert time strings to seconds - Uses
reducemethod to calculate total seconds - Uses
Math.floorand modulo operations to calculate hours, minutes, and remaining seconds
