JavaScript Compare ERROR

1

I'm trying to pass a for to validate a list that I need but I'm not able to make it work and I do not understand why yet.

I have the following code:

$('#aprovados').click( function(){
  $.getJSON($('#listeditappjobs').attr("data-list-app-my-jobs-url"),
    function(data){
      if (data){
        var apps = data.data
        console.log(apps[0])
        var infojob = data.datas
        console.log(infojob)
        var aprovados = []
        for(i = 0; i < apps.length; i++){
         if (infojob.distance >= apps[i].distance  &&
             infojob.xp <= apps[i].years_xp &&
             infojob.salary_min <= apps[i].pre_salary  &&
             infojob.salary_max >= apps[i].pre_salary)
            {aprovados.push(apps[i]); }
               };
        console.log(aprovados)
      }else{alert("LISTA vazia")
    }},
);
});

What I have to return is:

Object { distance: 1, escolaridade: "TecnologoCursando", user: "[email protected]", pre_salary: "1500.12", years_xp: 3 }

Object { distance: 2, xp: 3, salary_max: "1500.01", salary_min: "200.00" }
Array []

What am I doing wrong?

    
asked by anonymous 22.03.2018 / 04:45

1 answer

1

The problem is that you are comparing numbers as strings:

infojob.salary_min <= apps[i].pre_salary
       |                     |
     "200.00"            "1500.12"

infojob.salary_max >= apps[i].pre_salary
       |                     |
     "1500.01"            "1500.12"

Use parseFloat() to convert them to numbers:

if (infojob.distance >= apps[i].distance  &&
    infojob.xp <= apps[i].years_xp &&
    parseFloat(infojob.salary_min) <= parseFloat(apps[i].pre_salary)  &&
    parseFloat(infojob.salary_max) >= parseFloat(apps[i].pre_salary))
   { aprovados.push(apps[i]); }

However, if you observe, this if will not be true because the last condition is false :

parseFloat(infojob.salary_max) >= parseFloat(apps[i].pre_salary)
                  |                                 |
               1500.01                           1500.12

1500.01 is not >= than 1500.12 .

Example where all conditions are true:

var data = {
   data: [{
      distance: 1,
      escolaridade: "TecnologoCursando",
      user: "[email protected]",
      pre_salary: "1500.12",
      years_xp: 3
   }],
   datas: {
      distance: 2,
      xp: 3,
      salary_max: "1500.12",
      salary_min: "200.00"
   }
}

var apps = data.data;
console.log(apps[0]);
var infojob = data.datas;
console.log(infojob);
var aprovados = [];
for(i = 0; i < apps.length; i++){
   if (infojob.distance >= apps[i].distance  &&
       infojob.xp <= apps[i].years_xp &&
       parseFloat(infojob.salary_min) <= parseFloat(apps[i].pre_salary)  &&
       parseFloat(infojob.salary_max) >= parseFloat(apps[i].pre_salary))
   { aprovados.push(apps[i]); }
}
console.log(aprovados);
    
22.03.2018 / 11:13