javascript - 优化数组过滤

标签 javascript jquery

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

我想优化上面给出 result2 的过滤方法。

如您在 result1 中所见,可以用更少的迭代次数获得相同的结果。在我的示例中,它可能看起来不太像,但有大量列表,其中性能是一个问题。

我的问题:有什么方法可以优化 result2 的过滤,使其作为 result1 过滤?

最佳答案

您可以先构建一个匹配对象,然后重新使用它以避免循环:

var ob={};
filter.map(function(a,b){
  ob[a.propertyName]=a.value;
})

result2 =  $.grep(list, function(x){
   j++;
   return x.type === ob.tpye && x.mode === ob.mode && x.blah === ob.blah;
});


/* which has the console showing (and yes, they are the same two objects in both results): 
[Object] "iterations:" 6 
[Object] "iterations:" 6   */

已满:http://jsfiddle.net/SqJ2y/2/

关于javascript - 优化数组过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465317/

相关文章:

javascript - jQuery Ajax 登录中没有 'Access-Control-Allow-Origin' header

javascript - 如何从 MVC4 中的 Javascript 检查 View 模型中的模型值

javascript - 如何访问嵌套 {{#each}} 中的外部属性?

javascript - 为多个类调用单个函数

javascript - 随动态内容调整的 Jquery 粘性页脚

jQuery:转到目标为 ="_blank"的 URL

javascript - R:如何在 Shiny 中初始化数据表 FixedColumns javascript?

javascript - 尝试使用 REGEX 过滤字符串中的多个值

javascript - 即时调整形状大小

javascript - jQuery 可拖动 div 周围的区域变暗?