-4

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?

  • You may have to learn regular expressions, or do lots of conditional statements with `.indexOf(char) != -1`. – area28 Jun 17 '15 at 15:51
  • 1
    There are plenty of other post on SO that can help you. – shammelburg Jun 17 '15 at 15:52
  • 1
    Possible duplicate of [How can search a string to see if it contains all substrings?](http://stackoverflow.com/questions/18147499/how-can-search-a-string-to-see-if-it-contains-all-substrings) – apsillers Jun 17 '15 at 15:53
  • If you're reading this, @user4703663, please undelete your post. I was working off an incorrect copy. It works just fine and would be happy to upvote. – Andy Jun 17 '15 at 16:16
  • God, I feel really bad now. – Andy Jun 17 '15 at 16:37

1 Answers1

2

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);
Andy
  • 39,764
  • 8
  • 53
  • 80