I need help with this code in Js. this example :
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][counter] === "A"){
continue;
}
console.log(friends[index]);
}
When I did it the massage appear to me,
seventh_lesson.js:203 Uncaught TypeError: Cannot read properties of undefined (reading '0') at seventh_lesson.js:203.
and then I changed this line
if (friends[index][counter] === "A"){continue;
}
with this
if (friends[index].startsWith("A")){continue;}
and still doesn’t work, I don’t know why?
Is the reason there are numbers in the array?
You should increase the index at the end of the loop, otherwise you skip the first element and overshoot the last one.
while(index < friends.length){
if ( typeof friends[index] === "number"){
continue;
}
if (friends[index][counter] === "A"){
continue;
}
console.log(friends[index]);
index++;
}
A better way to iterate through the array would be a for...of loop, so you won't have to use the index at all.
for(const friend of friends)
if ( typeof friend === "number"){
continue;
}
if (friend[counter] === "A"){
continue;
}
console.log(friend);
}
Try this code
let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
let index = -1; // Here define index position is -1 because in the while loop first increase index
// // Output
// "1 => Sayed"
// "2 => Mahmoud"
while(index < friends.length-1){
index++;
if ( typeof friends[index] === "number"){
continue;
}
if (friends[index].charAt(0) === "A"){ // Here used charAt(0) is meance it will check only first letter is A or not If find a then it will continue
continue;
}
console.log(friends[index]);
}
OR
let friends = ["Ahmed", "Sayed", "Ali", 1, 2, "Mahmoud", "Amany"];
friends.filter((o)=>{
if(typeof(o)!="number"&&!o.startsWith("A"))
console.log(o)
})