["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
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);
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);
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.