Reputation: 109
I am trying to take a user inputed word, check it against all the words in an array and then remove the words in the array that contain any of the same letters with something along the lines of:
var words = [
// words go here
]
for (let a = 0; a <= inputWord.length; a++) {
for (let b = 0; b <= words.length; b++) {
if (!words[b].includes(inputWord[a])) {
words.splice(b, 1);
}
}
}
The browser console is giving me "TypeError: Cannot read property 'includes' of undefined." While testing I can print out input[A]
fine, and I can print out words[
random number of my choosing ]
fine, but when I try and print words[b]
it's coming up undefined.
Problem
I'm unable to figure out why words[b]
is undefined.
Upvotes: 2
Views: 4916
Reputation: 8239
Array indexing starts from 0.Run your loop from 0 - arr.length-1. The element at words[words.length] is undefined.
let words = [
// words go here
]
for (let a = 0; a < inputWord.length; a++) {
for (let b = 0; b < words.length; b++) {
if (!words[b].includes(inputWord[a])) {
words.splice(b, 1);
}
}
}
Upvotes: 2