I have a basic dataset stored in javascript that I want to filter based on user checked checkboxes. I know I can use jQuery's filter() function to filter the result set on multiple criteria, however the issue I'm running into is that the criteria would change depending on user input.
var myArray = [["Adelaide", 2, "yes", "female"],
["Ada", 2, "yes", "female"],
["Amanda", 1, "yes", "female"],
["Wolf", 3, "no", "male"],
["Rhonda", 1, "no", "female"]];
HTML:
<input id="rate-3" name="rating" type="checkbox" value="rate-3" />3 Stars<br />
<input id="rate-2" name="rating" type="checkbox" value="rate-2" />2 Stars<br />
<input id="rate-1" name="rating" type="checkbox" value="rate-1" />1 Star<br />
<a href="#" id="submitform">Submit Filters</a>
How would I pass multiple criteria to the .filter(function)? As an example, someone might select rate-1 and rate-3 checkboxes which is what I currently hard coded the function to look for, however I want it to be flexible depending on the user submitted input.
I guess I could just write a number of if/else statements but is there a more elegant way of doing this?
JQuery:
$("#submitform").click(function() {
var userSelectedFilters = new Object();
userSelectedFilters.rate3 = $("#rate-3").is(':checked');
userSelectedFilters.rate2 = $("#rate-2").is(':checked');
userSelectedFilters.rate1 = $("#rate-1").is(':checked');
var filteredArray = myArray.filter(
function(el) {
// currently hardcoded
return ((el[1] == 1) || (el[1] == 3));
}
);
});
filter()lets you pass a function in, instead of a selector. api.jquery.com/filter