代码之家  ›  专栏  ›  技术社区  ›  CodeSpent

过滤字母在所有相同位置的单词

  •  0
  • CodeSpent  · 技术社区  · 4 年前

    这是一个解决单词的挑战,我正试图用它来提高我的字符串算法技能,但我一直在思考如何让它适用于索引匹配的所有字符。

    假设我们有一系列单词。

    ['ducks', 'treks', 'tests', 'tease']
    

    我们知道 第一个字母 是一个 T ,以及 第二封信 是一个 E 所以我们应该得到的是 ['tests', 'tease'] .

    这是在使用Vue,所以 here's a reproduction of the component .以下仅为方法。

    
    fetchPotentialWords() {
    
          const potentialMatches = []
    
          // Get only words of the correct length
          let filteredWords = words.filter(x => x.length === this.letterCount)
    
          // Iterate correct letters to map their placement
          this.correctLetters.map((letter, index) => {
            // Return early if undefined
            if (letter === undefined) return;
    
            // Filter words where indexes match
            potentialMatches.push(...filteredWords.filter(x => x[index] === letter))
          })
          
          return potentialMatches
        }
    
    

    这种方法的问题在于,它没有考虑以前字母的索引,只是确保某个特定迭代的字母处于正确的索引。我想做些什么来确保所有索引在找到匹配项时通过向下筛选来匹配?

    1 回复  |  直到 4 年前
        1
  •  3
  •   CertainPerformance    4 年前

    检查一下 .every 其中一个 .correctLetters (如果定义了正确的字母)在适当的索引处匹配。不要使用 .map 对于副作用-由于您试图通过检查现有阵列中的哪一个与条件匹配来创建阵列,请仅使用 .filter .

    fetchPotentialWords(){
      return words
        .filter(word => 
          word.length === this.letterCount &&
          this.correctLetters.every((letter, i) => !letter || word[i] === letter)
        );
    }