如何在过滤器方法中返回与&&在回调函数中加入的布尔值?

时间:2019-03-27 21:07:01

标签: javascript loops filter callback higher-order-functions

我正在寻找一种生成布尔值的好方法,该布尔值最终将在过滤器方法的回调函数中使用&&运算符加入。

我试图遍历过滤条件,但是找不到将每个迭代结果合并为以下格式的方法:

return Boolean && Boolean && Boolean && Boolean && Boolean

因为+ = &&布尔值不起作用。

这是我所拥有的并且正在起作用:

//data I am filtering
this.preSearch = [
  ["The Lord of the Rings", "J. R. R. Tolkien", "English", "1955", "150 milionów"],
  ["Le Petit Prince (The Little Prince)", "Antoine de Saint-Exupéry", "French", "1943", "140 milionów"],
  ["Harry Potter and the Philosopher's Stone", "J. K. Rowling", "English",  "1997", "120 milionów"],
  ["The Hobbit", "J. R. R. Tolkien", "English", "1937", "100 milionów"],
  ["And Then There Were None", "Agatha Christie",   "English", "1939",  "100 milionów"],
  ["Dream of the Red Chamber",  "Cao Xueqin",   "Chinese", "1791", "100 milionów"]
]

//filters, that are set dynamically but let's pretend they are equal to
var filters = ["", "", "english", "19", "1"]

var searchdata = this.preSearch.filter(row => {
          return 
    row[0].toLowerCase().indexOf(filters[0].toLowerCase()) > -1 
    && row[1].toLowerCase().indexOf(filters[1].toLowerCase()) > -1 
    && row[2].toLowerCase().indexOf(filters[2].toLowerCase()) > -1 
    && row[3].toLowerCase().indexOf(filters[3].toLowerCase()) > -1 
    && row[4].toLowerCase().indexOf(filters[4].toLowerCase()) > -1
})

我需要可扩展且更优雅的解决方案,因此,如果我增强了过滤后的数组,则不必再用&&添加一行。

2 个答案:

答案 0 :(得分:4)

您可以将Array#every用于过滤器数组。

为了更快地进行检查,您可以预先将过滤器值转换为小写。

var preSearch = [["The Lord of the Rings", "J. R. R. Tolkien", "English", "1955", "150 milionów"], ["Le Petit Prince (The Little Prince)", "Antoine de Saint-Exupéry", "French", "1943", "140 milionów"], ["Harry Potter and the Philosopher's Stone", "J. K. Rowling", "English", "1997", "120 milionów"], ["The Hobbit", "J. R. R. Tolkien", "English", "1937", "100 milionów"], ["And Then There Were None", "Agatha Christie", "English", "1939", "100 milionów"], ["Dream of the Red Chamber", "Cao Xueqin", "Chinese", "1791", "100 milionów"]],
    filters = ["", "", "english", "19", "1"].map(s => s.toLowerCase()),
    result = preSearch
        .filter(row => filters.every((v, i) => row[i].toLowerCase().includes(v)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以这样应用Array.every()String.includes()来做到这一点:

var searchdata = this.preSearch.filter(row => {

    // this only returns true if our condition works for
    // index = 0, 1, 2, 3, 4
    return [0, 1, 2, 3, 4].every(index => {
        const rowContent = row[index].toLowerCase();
        const filterContent = filters[index].toLowerCase();

        // String.includes() is nicer than String.indexOf() here because
        // you don't need the ugly -1
        return rowContent.includes(filterContent);
    });
});