take array time with jQuery?

Asked

Viewed 138 times

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 answers

2


You can do it like this:

  • Creates a function to convert hh:mm in minutes
  • Creates another function to compare the minimum and maximum
  • It also spends the hours to choose (the array with all options) from the function it compares. So you get a pure function and 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);

  • 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?

  • @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 and 6:15 :)

  • @Does this function also work for this case?? https://answall.com/questions/213822/ajuda-com-filtro-em-json-com-jquery/213828#213828

  • @Newtech yes, you just have to change the logic of horasParaMinutos to generate a timestamp.

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

You are not signed in. Login or sign up in order to post.