如何过滤包含特定字符串模式的单词数组和另一个数组中的单词数组?



我有一堆单词。我可以在输入字段中输入文本,数组将根据我的请求进行过滤。这是容易的部分。

现在,我还可以选择其中一个建议的单词并将其推送到另一个选定单词数组中。一旦一个单词进入选定的数组,它就应该不再可用。

我写了这个:

const words = ["hello", "allo", "test", "cool", "top"]
const selected = ["hello"]
const availableWords = (term) => words.filter((w,i)=> w.includes(term) && !selected[i].includes(term))
availableWords("llo")
// expected output: ["allo"]
// actual output: "Cannot read property 'includes' of undefined"

如何解决这个问题?

如果实际单词匹配,则需要排除找到的选定单词。

const
availableWords = term => words.filter(w => w.includes(term) && !selected.includes(w)),
words = ["hello", "allo", "test", "cool", "top"],
selected = ["hello"];
console.log(availableWords("llo")); // ["allo"]

听起来这就是你想要的:

let availableWord2 = (term) => words.filter(w => !selected.includes(w))
.filter(w => w.includes(term))
availableWord2('llo') //["allo"]

说明:第一个筛选器筛选出所有已选择的单词。然后,第二个筛选器从其余列表中搜索输入的单词。

最新更新