2
I have that code:
var fhora = function(horamin, horamax){
var horas = ["11:20", "04:40", "22:30", "07:00"];
return horas;
};
how do I return only the hours that are between 05:00 and 23:30?
fhora("05:00", "23:30");
2
I have that code:
var fhora = function(horamin, horamax){
var horas = ["11:20", "04:40", "22:30", "07:00"];
return horas;
};
how do I return only the hours that are between 05:00 and 23:30?
fhora("05:00", "23:30");
2
You can do it like this:
hh:mm
in minutesExample:
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);
0
An alternative, using the 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"));
Yeah, like the hours are string and are in 24h format, a simple comparison between string is already sufficient to identify if a certain value is in the desired range.
Browser other questions tagged javascript jquery
You are not signed in. Login or sign up in order to post.
I published my reply and had not seen that yours also used the
filter
. You converted the values to minutes instead of simply comparing the strings for some particular reason?– Woss
@Andersoncarloswoss converted the strings because I like to compare numbers with the Type correct, and because it is safer for anyone who can read this post and will compare
7:0
and6:15
:)– Sergio
@Does this function also work for this case?? https://answall.com/questions/213822/ajuda-com-filtro-em-json-com-jquery/213828#213828
– usuario
@Newtech yes, you just have to change the logic of
horasParaMinutos
to generate a timestamp.– Sergio