Existing answers hardcode the hours minutes and seconds, but a dynamic approach is to split on the :
delimiter and accumulate, multiplying each chunk by 60 and adding it to the next chunk. After doing this, the last element contains the total seconds, which can be converted to h:m:s.
const sumToSeconds = times => {
return times.reduce((a, e) => {
const parts = e.trim().split(":").map(Number);
parts.forEach((e, i) => {
if (i < parts.length - 1) {
parts[i+1] += e * 60;
}
});
return parts.pop() + a;
}, 0);
};
const times = [
"4:50",
"2:02",
"1:38",
"2:49",
"2:49",
"2:13",
"2:20",
"2:12",
"2:44",
"4:23",
"55:23",
"1:01:02",
];
const totalSeconds = sumToSeconds(times);
console.log(
`${~~(totalSeconds / 60 / 60)} hours, ${
~~((totalSeconds / 60) % 60)} minutes, ${
~~(totalSeconds % 60)} seconds`
); // => 2 hours, 24 minutes, 25 seconds
The h:m:s part can be made dynamic too, if desired:
const sumToSeconds = times => {
return times.reduce((a, e) => {
const parts = e.trim().split(":").map(Number);
parts.forEach((e, i) => {
if (i < parts.length - 1) {
parts[i+1] += e * 60;
}
});
return parts.pop() + a;
}, 0);
};
const toHMS = time => {
const labels = ["hours", "minutes", "seconds"];
return Object.fromEntries(
labels.map((e, i) => [
e,
~~(time / 60 ** (labels.length - i - 1)) % 60,
])
);
};
const times = [
"4:50",
"2:02",
"1:38",
"2:49",
"2:49",
"2:13",
"2:20",
"2:12",
"2:44",
"4:23",
"55:23",
"1:01:02",
];
console.log(toHMS(sumToSeconds(times)));
// => { hours: 2, minutes: 24, seconds: 25 }
As an aside, if I may nitpick on your question a bit,
01:00:00
00:30:00
00:30:00
isn't a great test case to pick because it doesn't exercise the code thoroughly. A test with some hour and minute values would be better.