Reputation: 21
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?
Upvotes: 1
Views: 535
Reputation: 27222
You can simply achieve it with the help of Array.filter() along with Array.some() method.
Live Demo :
let words = ['the', 'dog', 'got', 'a', 'bone'];
const letters = 'ae';
const splittedLetters = letters.split('');
const res = words.filter(item => {
return splittedLetters.some(word => item.includes(word));
});
console.log(res);
Upvotes: 0
Reputation: 9
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']
Upvotes: -2
Reputation: 1075059
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));
Upvotes: 3