calebo
calebo

Reputation: 3442

Transform a string separated by semi colons with javascript

I have a string (which is a time) like such 01:02:3 that I would like to get a total number value in seconds. So expected output would be 3723.

const time = "1:02:3";

const timeNumeric = time.split(':').map(item => { 
  return Number(item)
});

function total() {
  var totalTime = 0;
  if (timeNumeric.length = 3) {
    const num1 = timeNumeric[0] * 3600
    const num2 = timeNumeric[1] * 60
    const num3 = timeNumeric[2]
    totalTime = num1 + num2 + timeNumeric[2]
  } else if (timeNumeric.length == 2) {
    const num2 = timeNumeric[1] * 60
    const num3 = timeNumeric[2]
    totalTime = num2 + num3
  } else if (timeNumeric.length == 1) {
    const num3 = timeNumeric[2]
    totalTime = num3
  } else {
    console.log('nothing')
  }
  console.log(totalTime)
}

Keep in mind, the value in the string might not always be 3 numbers, could be 2:45 or 30, which then the 3rd option value would not require any calculation.

Upvotes: 0

Views: 52

Answers (2)

Alex Dacre
Alex Dacre

Reputation: 86

Your code was right except for the current number. When you use * JavaScript attempts to convert to a number. However when you use + JavaScript attempts to convert to a String if one of the two variables is a String.

var getSeconds = function(time) {
    return time.split(':').reduce(function(prev, curr) { 
        return prev * 60 + parseInt(curr, 10)
    }, 0)
}

var total = getSeconds('01:02:03')
var total2 = getSeconds('2:34')

console.log(total, total2) // 3723 154

Upvotes: 1

thul
thul

Reputation: 1186

You need to convert the split strings into numbers before you can use the reduce function to multiply them out. Something like this:

const strNums = "01:02:3";
const multiplier = 3;

const arrayStrNums = strNums.split(':').map( item => {
    return Number(item) * multiplier;
});

const total = arrayStrNums.reduce((a, b) => {
    return a + b;
})

console.log(total);

Upvotes: 1

Related Questions