get array time with jQuery?

2

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");
    
asked by anonymous 21.06.2017 / 11:04

2 answers

2

You can do it like this:

  • Creates a function to convert hh:mm to minutes
  • Create another function to compare the minimum and maximum
  • It also passes the hours to choose (the array with all the options) to the function that compares. So you get a pure function and you have no side effects in the code.

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);
    
21.06.2017 / 11:15
0

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.

    
21.06.2017 / 13:25