Bopbop
Bopbop

Reputation: 83

How to reduce time using Javascript?

How can I use reduce() to calculate the total of all times (in string format) in the following array?

time["00:30", "01:45", "02:33"]

times.reduce((time, nextTime) => time + nextTime, 0)

I was thinking I need to split(":"), parseInt() and some more calculations or is there an easier way to do this?

Upvotes: 1

Views: 472

Answers (2)

Bopbop
Bopbop

Reputation: 83

This worked for me, this function timer is taking 2 times hh:mm:ss and splits it, divides, and then adds them together and after, it formats it to hh:mm:ss again

function timer(tempo1, tempo2) {
  var array1 = tempo1.split(":");

  var tempo_seg1 =
    parseInt(array1[0]) * 3600 + parseInt(array1[1]) * 60 + parseInt(array1[2]);

  var array2 = tempo2.split(":");

  var tempo_seg2 =
    parseInt(array2[0]) * 3600 + parseInt(array2[1]) * 60 + parseInt(array2[2]);

  var tempofinal = parseInt(tempo_seg1) + parseInt(tempo_seg2);

  var hours = Math.floor(tempofinal / (60 * 60));

  var divisorMinutes = tempofinal % (60 * 60);

  var minutes = Math.floor(divisorMinutes / 60);

  var divisorSeconds = divisorMinutes % 60;

  var seconds = Math.ceil(divisorSeconds);

  var counter = "";

  if (hours < 10) {
    counter = "0" + hours + ":";
  } else {
    counter = hours + ":";
  }

  if (minutes < 10) {
    counter += "0" + minutes + ":";
  } else {
    counter += minutes + ":";
  }

  if (seconds < 10) {
    counter += "0" + seconds;
  } else {
    counter += seconds;
  }

  return counter;
}

export default timer;

and on my React App I used this code to keep track of the times and add them calling the timer function

const updateTime = () => {
    let times = [];
    let times2 = [];
    if (todos.length > 1) {
      for (let i = 0; i < todos.length; i++) {
        times.push(todos[i].time + ":00");
      }
      times2 = times[0];
      for (let i = 1; i < times.length; i++) {
        times2 = timer(times2, times[i]);
      }
      times2 = times2.substr(0, 5);
    } else if (todos.length == 1) times2 = todos[0].time;
    else times2 = "No tasks";
    return times2;
  };

I only wanted hh:mm but for the sake of future implementation of seconds if needed, I'm going to add ":00" (seconds) and then remove it again using

times2 = times2.substr(0, 5);

Upvotes: 0

OldBuildingAndLoan
OldBuildingAndLoan

Reputation: 3022

If you can use an open JavaScript library like moment.js, the following is simple and preserves your string formatted times.

Note that I'm passing in "00:00" as the default value to reduce() so that times are calculated from a zero baseline, which also follows the string formatting that we'll use for all other values in the array.

const times["00:30", "01:45", "02:33"]

const totalTime = times.reduce((time, nextTime) => {
  return moment(time, "hh:mm")
          .add(nextTime, "hh:mm")
          .format("hh:mm");
}, "00:00");

console.log("total time -->", totalTime);

// total time --> "04:48"

If we added logging inside reduce() to view the accumulation of values:

"12:30"
"02:15"
"04:48"
"total time -->" "04:48"

Notice that the result after the first pass was "12:30". If all times in the array summed to less than one clock hour the end result may not be acceptable for your particular use case.

Upvotes: 1

Related Questions