score:-1

Accepted answer

The reason your code didn't work is because you are modifying original tableData while filtering, and using the modified tableData on subsequent filter button clicks.

You can avoid doing that by using a new array filteredTableData throughout your function.

var filteredTableData = tableData;

Declare above variable at start of your function, and replace tableData with filteredTableData everywhere in rest of your function.


No need to implement below changes, above fix will work. But you can follow below approach if you want to apply all property filters on each array element at once, or to keep the code more concise.

You can use Array.filter() to filter your data.

button.on("click", function () {
  d3.event.preventDefault();

  // Construct a filters object.
  var filtersObj = {
    "datetime": d3.select("#datetime").property("value"),
    "city": d3.select("#city").property("value"),
    "state": d3.select("#state").property("value"),
    "country": d3.select("#country").property("value"),
    "shape": d3.select("#shape").property("value")
  };

  // Remove properties which are undefined.
  for (var key in filtersObj) {
    if (!filtersObj[key]) {
      delete filtersObj[key];
    }
  }

  var filters = Object.entries(filtersObj);

  // Filter on properties which are defined.
  const filteredTableData = tableData.filter(item => 
    filters.every(([key, value]) => item[key] == value)
  );

  buildTable(filteredTableData);
}

You can also filter without using Object.entries() and Array.every().

// Filter on properties which are defined.
const filteredTableData = tableData.filter(item => {
  for (var key in filtersObj) {
    if (item[key] != filtersObj[key]) {
      return false;
    }
  }
  return true; 
});

Live Example:

var tableData = [
  { "city": "Chicago", "state": "Illinois", "country": "USA" },
  { "city": "Dallas", "state": "Texas", "country": "USA" },
  { "city": "Los Angeles", "state": "California", "country": "USA" },
  { "city": "San Francisco", "state": "California", "country": "USA" }
];

function filterData(inputDate, inputCity, inputState, inputCountry, inputShape) {
  // Construct a filters object.
  var filtersObj = {
    "datetime": inputDate,
    "city": inputCity,
    "state": inputState,
    "country": inputCountry,
    "shape": inputShape
  };

  // Remove properties which are undefined.
  for (var key in filtersObj) {
    if (!filtersObj[key]) {
      delete filtersObj[key];
    }
  }

  var filters = Object.entries(filtersObj);

  // Filter on properties which are defined.
  const filteredTableData = tableData.filter(item => 
    filters.every(([key, value]) => item[key] == value)
  );

  console.log(JSON.stringify(filteredTableData));

}

filterData(null, "Chicago", null, null, null);
filterData(null, null, "California", null, null);
filterData(null, null, "Texas", "USA", null);


Related Query

More Query from same tag