Sum of multiple times value
If the number of time values can vary between 3 and 4, you can modify the sumTime
function to accept an array of time values.
function sumTimes(timeArray) {
// Initialize total hours, minutes, and seconds
let totalHours = 0;
let totalMinutes = 0;
let totalSeconds = 0;
// Iterate through each time value in the array
timeArray.forEach(time => {
// Parse time value
const [hours, minutes, seconds] = time.split(':').map(Number);
// Add to the total
totalHours += hours;
totalMinutes += minutes;
totalSeconds += seconds;
});
// Handle carry-over from seconds to minutes
if (totalSeconds >= 60) {
totalMinutes += Math.floor(totalSeconds / 60);
totalSeconds %= 60;
}
// Handle carry-over from minutes to hours
if (totalMinutes >= 60) {
totalHours += Math.floor(totalMinutes / 60);
totalMinutes %= 60;
}
// Format result
const formattedResult = `${padZero(totalHours)}:${padZero(totalMinutes)}:${padZero(totalSeconds)}`;
return formattedResult;
}
// Helper function to pad single digits with zero
function padZero(num) {
return num < 10 ? `0${num}` : num;
}
// Example usage with an array of time values
const timeArray = ["03:47:29", "01:47:16", "02:30:45"];
const result = sumTimes(timeArray);
console.log(result);