http://jsfiddle.net/SqJ2y/
var list = [ { mode: 1, type: 'foo', blah: 1 }, { mode: 3, type: 'foo', blah: 1 }, { mode: 3, type: 'foo', blah: 1 }, { mode: 1, type: 'bar', blah: 1 }, { mode: 2, type: 'bar', blah: 0 }, { mode: 3, type: 'bar', blah: 1 } ]; var filter = [ { propertyName: 'mode', value: 1 }, { propertyName: 'type', value: 'foo' }, { propertyName: 'blah', value: 1 } ]; var i = 0; var result1 = $.grep(list, function(x){ i++; return x.type === 'foo' && x.mode === 1 && x.blah === 1; }); console.log(result1, 'iterations:', i); // 6 iterations var j = 0; var result2 = list; $.each(filter, function(k, filter){ result2 = $.grep(result2, function(listItem) { j++; return listItem[filter.propertyName] === filter.value; }); }); console.log(result2, 'iterations:', j); // 9 iterations
I would like to optimize my filtering method, which gives result2 above.
As you can see in result1 , the same result can be achieved with fewer iterations. In my example, this may not be so much, but you have large lists that have a performance problem.
My question is: is there a way to optimize filtering for result2 so that it works as filtering result1 ?