DoneDeal0
DoneDeal0

Reputation: 6257

How to filter an array of words that includes a specific string pattern and of words that are in another array?

I have an array of words. I can enter a text in an input field, and the array will be filtered based on my request. This is the easy part.

Now, I can also select one of the word proposed and push it into another array of selected words. As soon as a word goes into the selected array, it should not be available anymore.

I wrote this:

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"

How to fix this?

Upvotes: 0

Views: 200

Answers (2)

Yathi
Yathi

Reputation: 1041

Sounds like this is what you want:

let availableWord2 = (term) => words.filter(w => !selected.includes(w))
                                    .filter(w => w.includes(term))

availableWord2('llo') //["allo"]

Explanation: The first filter filters out all the words that are already selected. The second filter then searches for the word entered from the remaining list.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

You need to exclude the found word of selected if the actual word match.

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"]

Upvotes: 1

Related Questions