Filtering List By First Letter

379 Views Asked by At

I'm having a bit of trouble filtering my list. I want to filter it to where it checks the first letter of a word the user inputs and if that first letter is the same as the letter from the lettera list.

function checkWords {
  var wordsCreated = getText("Input");
  for (var i = 0; i < letters.length; i++) {
     var firstLetter = letters [i].substring(0,1);
     firstUserLetter = wordsCreated.substring(0,1);
     if (firstLetter==firstUserLetter) {
      // uses appendItem() to add a new item to the word list
      appendItem(guessedList, getText("Input"));
      setProperty("Input", "text", "");
      setText("Output", wordList.join("\n"));
      updateScore();
      }
  }
}

I tried everything but I can't seem to figure out why it's not filtering it to where it only adds the word to the list if the first letter of it corresponds with the random letter.

1

There are 1 best solutions below

0
Ronnie Royston On

var letters = ["a","b","c","d","e","f","g"];
var button = document.querySelector("button");
var resultArray = [];
button.addEventListener("click", function (evt) {
  var val = document.querySelector("input").value;
  let letter = letters[Math.floor(Math.random()*letters.length)];
  console.log("Random letter chosen was " + letter);
  if(val.charAt(0) === letter){
    resultArray.push(val);
  }
  console.log("Result list is: " + resultArray);
});
<input type="text" size="10">
<button>submit</button>