-2
["4", "5.67", "1:45.67", "4:43.45"]

I have this string array and i want to convert all of the strings to numbers with seconds format so it will become something like this

[4, 5.67, 105.67, 283.45]

how can i do it?

function hmsToSecondsOnly(str) {
    var p = str.split(':'),
        s = 0, m = 1;

    while (p.length > 0) {
        s += m * parseInt(p.pop(), 10);
        m *= 60;
    }

    return s;
}

I found this but it seems to only work in MM:SS format like 1:40 but i want convert strings in x:xx.xx format

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
  • Looking for https://stackoverflow.com/questions/9640266/convert-hhmmss-string-to-seconds-only-in-javascript? – heartleth Apr 10 '21 at 10:03
  • 1
    Coder, need to clarify the requirements a bit. Is it correct to convert `"1:45.67"` to `105.67`? it looks like `"4:43.45"` was considered differently – Scott Anderson Apr 10 '21 at 10:08
  • @ScottAnderson yeah ```1:45.67``` to ```105.67``` is correct and ```4:43.45``` to ```283.45``` is also correct – I_love_vegetables Apr 10 '21 at 10:19

3 Answers3

1

You can try using map() like the following way:

var data = ["4", "5.67", "1:45.67", "4:43.45"];
data = data.map(function(item){
  //split to get the hour
  var a1 = item.split(':');
  //split to get the seconds
  var a2 = item.split('.');
  //check the length
  if(a1.length > 1){
    //split to get minutes
    var t = a1[1].split('.');
    //calculate, cast and return
    return +((a1[0]*60 + +t[0]) + '.' + a2[a2.length - 1]);
  }
  else return +item;
});

console.log(data);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

You could map the formatted time values.

const 
    data = ["4", "5.67", "1:45.67", "4:43.45"],
    result = data.map(time => time
        .split(':')
        .map(Number)
        .reduce((m, s) => m * 60 + s)
    );

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

Another simple solution with RegEx.

const input = ["4", "5.67", "1:45.67", "4:43.45"]
const result = input.map(ele => ele.replace(/^(\d+):(\d+[.]\d*)$/, (m, g1, g2) => `${g1 * 60 + parseFloat(g2)}`));

console.log(result)
Ravikumar
  • 2,085
  • 12
  • 17