Convert time into mins
- 4 years ago
Try this:
$timestr.split(’ ').reduce((accum,curVal,curIdx,array) => accum + (curIdx % 2 == 0 ? parseInt(curVal) * (array[curIdx+1] == “hours” ? 60 : (array[curIdx+1] == “minutes” ? 1 : 0)): 0), 0)Explanation of solution:
$timestr is the input string you provided, ex: 2 hours 35 seconds
.split(’ ') converts the string to an array of the words: [“2”, “hours”, “35”, “seconds”]
.reduce is an Array function that let’s you collapse the array to a scalar element (See Array Functions - reduce)
In the reduce, we’re examining each array element, parsing every other element as an integer and multiplying the value appropriately for hours, adding minutes, and ignoring secondsAs with any programming tool, there are multiple ways to achieve the desired result, but this is the first I thought of and I believes accomplishes what you want.