JavaScript Snippet - Parse Time Format Into Number Of Seconds

Posted at

Nice little explanation by example:

"01:01:30".split(":").reverse().reduce(function(previous_value, current_value, current_index, array){
current_value = Number(current_value);
return previous_value + (current_value * Math.pow(60, current_index))
}, 0);


which is 3690 seconds.




this code will easily sort all of the youtube videos by length, regardless where you are, as long there are videos on the page currently viewed...

NodeList.prototype.map = Array.prototype.map;

function parse_to_seconds(time_string){ /* "01:01:30" --- 3690 */
return
time_string.split(":").reverse().reduce(function(previous_value, current_value, current_index, array){
current_value = Number(current_value);
return previous_value + (current_value * Math.pow(60, current_index))
}, 0);
}

var elements = document.querySelectorAll('li.channels-content-item').map(function(element){return element});

elements = elements.sort(function(a,b){
return parse_to_seconds(a.querySelector('.video-time').innerText) - parse_to_seconds(b.querySelector('.video-time').innerText)
});


you now have to clear and clone each of the elements, and apply them into the video container :) see other examples in this blog for similar implementations :) :)