简体   繁体   English

如何在循环中链接lazy.js中的多个过滤器(来自数组)

[英]How to chain multiple filters in lazy.js in a loop (from array)

I have an array that contain filter functions that need to be applied to an array of items in Lazy.js. 我有一个数组,其中包含需要应用于Lazy.js中的项目数组的过滤器函数。 I've tried using a for-loop but only the last filter is applied. 我尝试过使用for循环,但只应用了最后一个过滤器。

function (searchText) {
    var result = Lazy(input);

    for (var query of this.querylist) {
        result = result.filter((item) => {
            return query.filterFunc(item, searchText, query.compareFunc);
        });
    }

    return result.toArray();
}

Is there a way of applying a list of filters without hardcoding the chaining? 有没有办法在不对链接进行硬编码的情况下应用过滤器列表?

Here is a fiddle showing the issue 这是一个显示问题的小提琴

You can use reduce to iterate over the filters and create a resulting one by applying each one to the previous one. 您可以使用reduce来迭代过滤器,并通过将每个过滤器应用于前一个过滤器来创建结果过滤器

var result = Lazy(contentArray);

var allFilters = filters.reduce(function(acc, current) {
    return acc.filter((item) => current.filterFunc(item)); // return the last one with the current filter applied
}, result); // start with the original one


console.log(allFilters.toArray())

You can find an updated fiddle here . 你可以在这里找到一个更新的小提琴。

The reduce is just a nicer and more generic way of this: reduce只是一种更好,更通用的方式:

var allFilters = result
                  .filter(filters[0])
                  .filter(filters[1])
                  .filter(filters[2]);

Lazy.js will not call the filters until you call toArray or forEach. 在调用toArray或forEach之前,Lazy.js不会调用过滤器。 I put some logs in this example . 我在这个例子中放了一些日志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM