2

I have such array with time:

// hours, minutes, seconds
let arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]

How I can get the sum of these elements?

output: "06:30:55"
  • 2
    Have you tried anything to do? You could loop through it, split it (convert to seconds), sum it, at the end you can format it in every way you wish from seconds.. – Ultrazz008 Mar 03 '21 at 11:57
  • Strings themselves don't have any meaning. Convert each string to a timestamp, add the timestamps together and format the result to the output. – Emiel Zuurbier Mar 03 '21 at 11:59
  • See https://stackoverflow.com/a/57571687/2494754 – NVRM Mar 03 '21 at 12:22

5 Answers5

2

Please try with this code.

let arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]
let sum = "";
for (let i = 0; i < arr.length; i++) {
    if(i == 0){
        sum = arr[i];
        continue;
    }else{
        var a = sum.split(":");
        var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
        var b = arr[i].split(":");
        var seconds2 = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
        var date = new Date(1970,0,1);
        date.setSeconds(seconds + seconds2);
        sum = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
    }
}
console.log(sum);
Aman Gojariya
  • 1,289
  • 1
  • 9
  • 21
2

As mentioned in the comments, the easiest way is to convert your array of durations into seconds, sum them up to get total seconds, and then parse the total seconds into the HH:MM:SS format that you desire.

There are a few steps:

  1. Create a function that parses seconds from duration
  2. Use Array.prototype.reduce to get total seconds from your array of duration, while applying the method we created in step 1.
  3. Parse the total seconds into desired format from step 2. You can use String.prototype.padStart() to achieve the two-digit output per time unit.

Here is a proof-of-concept example:

const arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]

/**
 * @method
 * Pads a given number to 2 digits with leading zeros
 */
function padNumber(num) {
  return num.toString().padStart(2, '0');
}

/**
 * @method
 * Gets the number of seconds from a duration in the format of HH:MM:SS
 */
function getSecondsFromDuration(duration) {
  const [ hours, minutes, seconds ] = duration.split(':').map(n => +n);
  
  return hours * 60 * 60 + minutes * 60 + seconds;
}

/**
 * @method
 * Formats a given duration, in seconds, into HH:MM:SS string
 */
function getDurationFromSeconds(seconds) {
  const hours = Math.floor(seconds / 3600);
  seconds -= hours * 3600;
  
  const minutes = Math.floor(seconds / 60);
  seconds -= minutes * 60;
  
  return `${padNumber(hours)}:${padNumber(minutes)}:${padNumber(seconds)}`;
}

const totalSeconds = arr.reduce((acc, cur) => {
  return acc + getSecondsFromDuration(cur);
}, 0);

console.log(getDurationFromSeconds(totalSeconds));
Terry
  • 63,248
  • 15
  • 96
  • 118
1

You could take an array of factors for gettign all seconds and build a new string with smaller units.

let array = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"],
    factors = [3600, 60, 1],
    seconds = array.reduce((seconds, time) => time.split(':').reduce((s, t, i) => s + t * factors[i], seconds), 0),
    result = factors.map(factor => {
        const value = Math.floor(seconds / factor);
        seconds -= value * factor;
        return value.toString().padStart(2, 0);
    }).join(':');

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

let arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]
let h=0,m=0,s=0;

arr.map((value,i)=>{
  h=h+ +value.split(":")[0];
  m=m+ +value.split(":")[1];
  s=s+ +value.split(":")[2];
})
console.log(h+":"+m+":"+s)

this may help you add a + in front of it will convert it into Number

Aashiq Otp
  • 85
  • 1
  • 10
0

You can combine map and reduce to sum your times and convert them to a Date afterwards:

const res = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"].map(element => {
  const tmp = element.split(":")
  return (+tmp[0]) * 60 * 60 + (+tmp[1]) * 60 + (+tmp[2])
}).reduce((acc, current) => acc + current)

const date = new Date(res*1000)
const minutes = date.getMinutes();
const hours = date.getHours()-1; // note the -1 to get the time not the current hour
const seconds = date.getSeconds();
console.log("Duration: ", `${hours}:${minutes}:${seconds}`)
messerbill
  • 5,499
  • 1
  • 27
  • 38