let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = 0;
let counter = 0;
// Output
"1 => Sayed"
"2 => Mahmoud"
while (index < friends.length) {
index++
if (typeof friends[index] === "number") {
continue;
}
if (friends[index].startsWith(friends[counter][counter])) {
continue;
}
console.log(friends[index])
}
And i Expect to get this output.
"1 => Sayed"
"2 => Mahmoud"
but console gave me this error Uncaught TypeError: Cannot read properties of undefined (reading ‘startsWith’)
2
Answers
Try adding friends[index] to your check. Also, your loop condition should be friends.length – 1
Your problem is, that you increment the index at the start of the loop instead of at the end. This means, that when you are at index 6 it still satisfys the while condition and then in the loop gets incremented to 7 which is outofbounds for the friends Array. My solution would be to switch from a while loop to a for loop.