'Not sure why this code isnt working. The program should search through this word list and remove any words that include the letter A
This is being done on code.org, for some reason it removes some words with the letter A but not all, im not sure why it wont work.
var wordList = ["abase", "abate", "abbey", "abbot", "abhor", "abide", "abled", "abode",
"abort", "about", "above", "abuse", "abyss", "acorn", "acrid", "actor", "acute", "adage",
"adapt", "adept", "admin", "admit", "adobe", "adopt", "adore", "adorn", "adult", "affix",
"afire", "afoot", "afoul", "after", "bulge", "bulky", "bully", "bunch", "bunny", "burly",
"burnt", "burst", "bused", "bushy", "butch", "butte", "buxom", "buyer", "bylaw", "cabal",
"cabby", "cabin", "cable", "cacao", "cache", "cacti", "pique", "setup", "seven", "sever",
"wrote", "wrung", "wryly", "yacht", "yearn",
"yeast", "yield", "young", "youth", "zebra", "zesty", "zonal"];
var wrongLettersList = ["a"];
var unsureLettersList = [];
var goodLettersList = [];
onEvent("wrongLetterInput", "input", function( ) {
appendItem(wrongLettersList, getText("wrongLetterInput"));
setProperty("wrongLetterInput","text", "");
setProperty("wrongLetterInput", "placeholder", "Letters inputted: "+wrongLettersList);
listFilter(wrongLettersList, unsureLettersList, goodLettersList);
});
function listFilter(wrongLetters, unsureLetters, goodLetters) {
for(var j = 0; j<wordList.length; j++) {
if(wordList[j].includes(wrongLetters[0])){
wordList.splice(j, 1);
}
}
console.log(wordList);
}
Solution 1:[1]
That's because you skip one word once you splice. The easy, but not the best choice is:
function listFilter(wrongLetters, unsureLetters, goodLetters) {
for(var j = 0; j<wordList.length; j++) {
if(wordList[j].includes(wrongLetters[0])){
wordList.splice(j, 1);
j-=1; // ---> decrement 1 from j so you don't skip a word
}
}
console.log(wordList);
}
But definitely, as above said, using filter is much easier and readable.
return wordList.filter(w => !w.includes(wrongLettersList[0]));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Simon G. |
