Home > Back-end >  Determine which strings contain the following characters in a list
Determine which strings contain the following characters in a list

Time:08-01

I am trying to write javascript code that allows me to extract which words (given as a list) contain either 1 or more characters in a given list of words.

function filterWords(words, letters) {
    var myArrayOfLetters = Array.from(letters)

    var output;
    for(var i = 0; i<myArrayOfLetters.length;   i)
    {
        output = words.filter(word => word.includes(myArrayOfLetters[i]))
    }

    return output;
}

This is the code I have so far but it is not working.

This is an example of the input and the output required:

words = ['the','dog','got','a','bone']
letters = 'ae'

output = ['the','a','bone']

As you can see the output contains all the words that have either 'a' or 'e' in them or both.

How would I go about solving this issue?

CodePudding user response:

You're on the right track, but you have your loops backward. You want to use the filter as the outer loop, and the loop over the array of letters as the inner loop, since you want to know if a word has any of those letters in it. The inner loop can be a call to the some method rather than an explicit loop:

function filterWords(words, letters) {
    const myArrayOfLetters = Array.from(letters);
    const output = words.filter((word) =>
         myArrayOfLetters.some((letter) => word.includes(letter))
    );
    return output;
}

some returns true if the callback ever returns true (or any truthy value), or false if the callback never does.

Live Example:

function filterWords(words, letters) {
    const myArrayOfLetters = Array.from(letters);
    const output = words.filter((word) => myArrayOfLetters.some((letter) => word.includes(letter)));
    return output;
}
const words = ["the", "dog", "got", "a", "bone"];
const letters = "ae";
console.log(filterWords(words, letters));

Here's an example with a word that has both a and e in it; note it's only included once:

function filterWords(words, letters) {
    const myArrayOfLetters = Array.from(letters);
    const output = words.filter((word) => myArrayOfLetters.some((letter) => word.includes(letter)));
    return output;
}
const words = ["the", "dog", "got", "a", "really", "nice", "bone"];
const letters = "ae";
console.log(filterWords(words, letters));

CodePudding user response:

let words = ['javascript', 'java', 'ruby', 'python', 'php'];
let filterWords =(words, chars) => {
      return words.filter(word => word.split('').some(char => chars.includes(char)));
}
console.log(filterWords(words, 'pa')); //['JavaScript', 'Java', 'Python', 'PHP']
  • Related