CodeSpent
CodeSpent

Reputation: 1904

Filtering words that have letters in the all of the same positions

This is for a Wordle solving challenge I'm trying to use to improve my string algo skills, but I'm stuck on how I can make this work for ALL characters where the indexes will match.

Lets say we have an array of words.

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

We know that the 1st letter is a T, and the 2nd letter is an E, so what we should get back is ['tests', 'tease'].

This is using Vue, so here's a reproduction of the component. Below is the method alone.


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
    }

The issue with this approach is that it doesn't take into consideration the indexes of previous letters, it just makes sure that the letter of one particular iteration is at the correct index. What would I want to do to ensure that all indexes match by filtering down as matches are found?

Upvotes: 0

Views: 466

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371049

Check that .every one of the .correctLetters (if the correct letter is defined there) matches at the appropriate index. Don't use .map for side effects - since you're trying to create an array by checking which of an existing array matches a condition, use only .filter.

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

Upvotes: 3

Related Questions