如何返回与&&过滤器方法中的内部回调函数? [英] How to return booleans joined with && inside callback function in filter method?
问题描述
我正在寻找一种生成布尔值的优雅方法,该布尔值最终将使用&&过滤器方法中我的回调函数中的运算符.
I am looking for an elegant way to generate booleans that will eventually be joined using && operator inside my callback function in filter method.
我试图遍历过滤条件,但找不到将每个迭代结果合并为以下格式的方法:
I tried to loop through the filter conditions but I cannot find a way to join each iteration result into the following format:
return Boolean && Boolean && Boolean && Boolean && Boolean
因为+ =&&布尔无效.
Becasue += && Boolean doesn't work.
这就是我所拥有的并且正在起作用:
Here is what I have and what is working:
//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
})
我需要可扩展性和更优雅的解决方案,因此我不必在&&中添加另一行如果我增强过滤后的数组.
I need scalable and way more elegant solution so I will not have to add another line with && if I enhance my filtered array.
推荐答案
You could use Array#every
for the filters array.
为了更快地进行检查,您可以预先将过滤器值转换为小写.
For a faster check, you could convert the filter values to lowercase in advance.
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; }
这篇关于如何返回与&&过滤器方法中的内部回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!