I have this code:
var fhora = function(horamin, horamax){
var horas = ["11:20", "04:40", "22:30", "07:00"];
return horas;
};
How do I get back to the hours between 05:00 and 23:30?
fhora("05:00", "23:30");
I have this code:
var fhora = function(horamin, horamax){
var horas = ["11:20", "04:40", "22:30", "07:00"];
return horas;
};
How do I get back to the hours between 05:00 and 23:30?
fhora("05:00", "23:30");
You can do it like this:
hh:mm
to minutes Example:
var horas = ["11:20", "04:40", "22:30", "07:00", "23.:45"];
function horasParaMinutos(str) {
var horas = str.split(':').map(Number);
return horas[0] * 60 + horas[1];
}
var fhora = function(horamin, horamax, arr) {
horamin = horasParaMinutos(horamin);
horamax = horasParaMinutos(horamax);
return arr.filter(function(hora) {
hora = horasParaMinutos(hora);
return hora >= horamin && hora <= horamax;
});
};
var res = fhora("05:00", "23:30", horas);
console.log(res);
An alternative, using Array.prototype.filter
, would be:
function fhora (horamin, horamax)
{
return ["11:20", "04:40", "22:30", "07:00", "23:45"].filter(hora => hora >= horamin && hora <= horamax);
};
console.log(fhora("05:00", "23:30"));
Because the times are string and are in 24h format, a simple comparison between string is enough to identify if a given value is in the desired range.