-2

So far I have been able to find the sum of min and sec store in array

var time = ["13:24", "4:28", "7:29"];
var min = 0;
var sec = 0;
for (k in time){
    min += +time[k].split(":")[0];
    sec += +time[k].split(":")[1];
}
var rem = sec % 60;
min += rem;

alert(min+'-'+sec);  //25-81  

my desired output it 25-21

ozil
  • 6,930
  • 9
  • 33
  • 56

2 Answers2

1

I think the desired o/p is 25-21

var time = ["13:24", "4:28", "7:29"];
var min = 0;
var sec = 0;

var minsec = time.forEach(function(time) {
  var parts = time.split(":")
  min += +parts[0];
  sec += +parts[1];
});

//Add the whole minutes from the seconds ie if seconds is 130 then 2 minuste to be added to min
min += Math.floor(sec / 60);
//then the rest 10 secs to be added to sec
sec = sec % 60;

alert(min + '-' + sec);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • For in is not recommended on arrays. Here is a forEach version https://jsfiddle.net/mplungjan/wL9bb8ab/ ;) – mplungjan Jun 03 '15 at 12:58
0

Your sum is wrong. You're adding the modulo of sec to min. That means if you were on 59 seconds, you'd add 59 minutes to your sum.

Instead you should add the division of sec, and set sec to the modulo:

min += Math.floor(sec / 60);
sec %= 60;

This way 69 seconds would translate to 1 minute and 9 seconds, whereas your current code would compute 9 minutes and 69 seconds.

Bilal Akil
  • 4,716
  • 5
  • 32
  • 52