How to sum time string in an array?
You can treat time as moment durations that can be summed up:
const any = ['7:20', '7:52', '5:03', '1:01', '9:02', '6:00'];
const sum = any.reduce((acc, time) => acc.add(moment.duration(time)), moment.duration());
console.log([Math.floor(sum.asHours()), sum.minutes()].join(':'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
You could use reduce
method by passing a callback function.
let arr= ["7:20", "5:50", "6:30"];
toSeconds = (str) => {
str = str.split(':');
return (+str[0]) * 60 + (+str[1]);
}
toHHss = (seconds) => {
let minutes = parseInt(seconds/60);
seconds = seconds - minutes*60;
return minutes + ':' + seconds;
}
let result = arr.reduce((r,elem) => r + toSeconds(elem), 0);
console.log(toHHss(result));