I have a bunch of filter criteria stored in an object. The criteria changes from time to time, so I can't have a static filter (ie: price > 5 && price < 19 && ...).
var criteria = {
price: {
min: 5,
max: 19
},
age: {
max: 35
}
};
I then have a loop setup to filter through an array based on the criteria and return the filtered array:
var filtered = [];
var add = true;
for (var i=0; i < data.length; i++ ){
add = true;
var item = data[i];
for (var main in criteria){
for (var type in criteria[main] ){
if ( type === 'min') {
if ( !(item[main] > criteria[main][type]) ) {
add = false;
break;
}
} else if ( type === 'max') {
if ( !(item[main] < criteria[main][type]) ) {
add = false;
break;
}
}
}
}
if (add) {
filtered.push(item);
}
}
Is there a more efficient way to setup the filter conditionals ahead of time (ie: item.price > 5 && item.price < 19 && item.age < 35) and then filter the array? As opposed to what I'm currently doing and referencing the object during each array loop - which is inefficient with all the conditionals and sub-loops.
See my jsbin - http://jsbin.com/celin/2/edit .