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 filter method that gives result2 above.
As you can see in result1, the same result can be acheived with less iterations. It might not look like much in my example, but have large lists where performance is an issue.
My question: Is there any way to optimize the filtering for result2 so that it works as the result1 filtering?
evalprobably you can create the filter callback dynamically