我有几个由100个字符串组成的数组,其中包含我使用FETCH检索到的注释。(称为comments
)和另一个包含10,000个关键字的数组。(称为关键字
)
对于数组中的每个注释,我要检查它包含哪些关键字。(我需要知道它包含的所有关键字,但不需要知道它出现的次数)
最快的方法是什么?
我尝试过foreach
在彼此之间循环:
keywords.forEach(word => {
comments.forEach(comment => {
if(comment.includes(word)) //call a function
}
})
以及之间的循环:
for(i = 0; i < keywords.length; i++) {
for(j = 0; j < comments.length; j++){
if(comments[j].includes(keywords[i])) //call a function
}
}
对于这两个,我都尝试过切换内部循环和外部循环。
我还尝试使用关键字构建正则表达式,并使用matchall
和for..of
循环进行匹配。
keywords.forEach(word => regex = regex + `(^|\\b)${word}(\\b|$)|`)
comments.forEach(comment => {
const matches = comment.matchAll(regex)
for (const match of matches){
//call a function
}
})
这些都在我最初测试的10个关键字的时候起作用,但是很明显,对于10,000个关键字,这将花费更长的时间。最有效的方法是什么?
这对我来说都是很新的,所以有可能我错过了一些明显的东西!
谢谢
请尝试使用集
。我已经在关键字
数组中创建了一个集
。现在,对于注释
数组中的每个单词,我都可以在集
中查找它是否包含该单词。
null
const keywords = ["java", "golang", "python", "ruby"];
const comments = ["I love java", "Golang is by google", "Python bit me hard"];
const hash = new Set(keywords.map((k) => k.toLowerCase()));
const test = (w) => console.log(w);
comments.forEach((c) =>
c.split(" ").forEach((w) => hash.has(w.toLowerCase()) && test(w))
);