Let's say i have the letters a,b,s,d (say)
I have 100s of words in an array.
I want to use js to search for a word containing all the letters, and only if all letters are met, then return that word.
How do i do it?
Let's say i have the letters a,b,s,d (say)
I have 100s of words in an array.
I want to use js to search for a word containing all the letters, and only if all letters are met, then return that word.
How do i do it?
.indexOf(char) != -1
.
– area28
Commented
Jun 17, 2015 at 15:51
OK, so here's an expanded version of the code originally posted by user4703663. I wanted to wait until they had a chance to undelete their answer but they never did.
var words = ['absd', 'dfsd', 'dsfefe', 'dfdddr', 'dfsgbbgah', 'dfggr'];
var str = 'absd';
function find(words, str) {
// split the string into an array
str = str.split('');
// `filter` returns an array of array elements according
// to the specification in the callback when a new word
// is passed to it
return words.filter(function(word) {
// that callback says to take every element
// in the `str` array and see if it appears anywhere
// in the word. If it does, it's a match, and
// `filter` adds that word to the output array
return str.every(function(char) {
return word.includes(char);
});
});
}
const output = find(words, str); // [ "absd", "dfsgbbgah" ]
console.log(output);