如何在filter方法中返回用回调函数内的&&加入的布尔值?

问题描述 投票:1回答:2

我正在寻找一种优雅的方式来生成布尔值,最终将使用过滤器方法中的回调函数内的&&运算符进行连接。

我试图循环过滤条件,但我找不到将每个迭代结果加入以下格式的方法:

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
})

我需要可扩展的方式和更优雅的解决方案,所以如果我增强我的过滤数组,我将不必添加另一行&&。

javascript loops filter callback higher-order-functions
2个回答
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
投票

你可以通过像这样应用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);
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.