最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - How to search for letters in words using javascript? - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question asked Jun 17, 2015 at 15:48 Ashwin AlaparthiAshwin Alaparthi 112 silver badges5 bronze badges 5
  • You may have to learn regular expressions, or do lots of conditional statements with .indexOf(char) != -1. – area28 Commented Jun 17, 2015 at 15:51
  • 1 There are plenty of other post on SO that can help you. – shammelburg Commented Jun 17, 2015 at 15:52
  • 1 Possible duplicate of How can search a string to see if it contains all substrings? – apsillers Commented Jun 17, 2015 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 Commented Jun 17, 2015 at 16:16
  • God, I feel really bad now. – Andy Commented Jun 17, 2015 at 16:37
Add a ment  | 

1 Answer 1

Reset to default 4

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);

发布评论

评论列表(0)

  1. 暂无评论