如何解决从数组中过滤出多个文本值
我需要过滤一个数组,以便某些值在包含选定的单词或短语时不会得到输出。例如,如果我的数组类似于 ["John Smith","Bob Smith","John Doe","Dave Jones"]
,我可能想要排除包含 Bob 或 Dave 的值。
目前,要做到这一点,我有以下几点:
const filtered =
names.filter(
myArray.toLowerCase().indexOf('bob') === -1
&& myArray.toLowerCase().indexOf('dave') === -1
);
let content = '';
filtered.forEach(item => {...}
这很好,而且很有效,但是如果我要增加单词的数量来过滤掉,这将变得很冗长。
我想我可以通过使用数组过滤来解决这个问题
myArray.toLowerCase().indexOf(['bob','dave']) === -1
事实证明,这根本不返回任何内容。于是继续尝试
['bob','dave'].some(x => myArray.toLowerCase().indexOf(x) === -1)
但这也失败了。我有一个想法,这些可能失败的原因是逻辑以某种方式寻找这两个值,但我既无法证明这一点,也无法解决它。
解决方法
使用正则表达式最容易找到复杂的字符串,它还有一个内置的“忽略大小写”标志,可以从字符串数组中组合。
const names = ["John Smith","Bob Smith","John Doe","Dave Jones"];
const exclude = ["bob","dave"];
const excludeRegex = new RegExp(exclude.join("|"),"i"); // finds strings matching "bob" or "dave" ignoring case
const filtered = names.filter(n => !excludeRegex.test(n)); // Regexp.test(str) returns true if the search finds any matches in str
console.log(filtered)
您可以使用 for 循环检查所有单词。它的函数可能如下所示:
function filter(names,blacklist) {
return names.filter(name => {
for (const word of blacklist) {
if (name.toLowerCase().includes(word.toLowerCase())) return false;
}
return true;
});
}
添加到@LaytonGB 答案中,您可以使用 rest 参数使其成为一个函数
function filterNames(arr,...arg) {
let regex = new RegExp(arg.join("|"),"i");
return arr.filter(n => !regex.test(n));
}
let arr = ["John Smith","bOb Smith","Dave Jones","Mike Caw","Arron Crybaby","King George","PaPa Murphy" ]
console.log(filterNames(arr,'smith','Doe','mike','king'))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。