Alexg2195
Alexg2195

Reputation: 605

Why doesn't this work? Filtering data

I am trying to match up 3 inputs to a set of data. Only if all three meet the criteria will it add all those three criteria to results. Those will be displayed later. I shortened the data set to one object for simplicity right now. Thank you!

var departureDate = $("#departure-date").val();
var returnDate = $("#return-date").val();
var city = $("#city").val();

var places = [{
  place: "New York City",
  avalibleArival: ["3 December, 2015", "4 December, 2015"],
  avalibleReturn: ["4 December, 2015", "6 December, 2015"]
}];

var results = [];
places.forEach(function (x) {
  if (x.place === city) {
    console.log("found city");
    places.forEach(function (y) {
      if (y.avalibleArival === departureDate) {
        console.log("Found correct Departure Date");
        places.forEach(function (z) {
          if (z.avalibleReturn === returnDate) {
            console.log("yay you found a Full match");
            results.push([x, y, z]);
          }
        });
      }
    });
  }
});

Upvotes: 0

Views: 49

Answers (1)

Jamiec
Jamiec

Reputation: 136074

2 major things are wrong with your code, one stops it working the other is just not necessary

  1. In the code if (z.avalibleReturn === returnDate) { and similar for avalibleArival you are comparing a string to an array, that will never equate true

  2. You are looping over the places array inside each loop of the places array - this is not only unnecessary, but highly inefficient. You don't need to do it.

I think what you're after is along the lines of

places.forEach(function (x) {
  if (x.place === city) {
    console.log("found city");
    if(x.avalibleArival.indexOf(departureDate) > -1){
        console.log("Found correct Departure Date");
        if(x.avalibleReturn .indexOf(returnDate) > -1){
            console.log("yay you found a Full match");
            results.push([x, y, z]);
        }    
    }    
  }
});

Upvotes: 2

Related Questions