-3
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')

VLAZ
  • 26,331
  • 9
  • 49
  • 67

2 Answers2

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.

let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let counter = 0;

for (let index = 0; index < friends.length; index++) {
    if (typeof friends[index] === "number") {
        continue;
    }
    if (friends[index].startsWith(friends[counter][counter])) {
      continue;
    }
    console.log(friends[index])
}
timmmmmb
  • 674
  • 7
  • 26
0

Try adding friends[index] to your check. Also, your loop condition should be friends.length - 1

let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = 0;
let counter = 0;

while (index < friends.length -1) {
    index++
    if (typeof friends[index] === "number") {
        continue;
    }
    if (friends[index] && friends[index].startsWith(friends[counter][counter])) {
      continue;
    }
    console.log(friends[index])
}
Tejeshree
  • 942
  • 6
  • 9