I am trying to print out all countries which end with 'land' from the countries array below:
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya'
]
newArr = [];
for (let i = 0; i <= countries.length; i++){
console.log(countries[i])
if (countries[i].endsWith('land') === true){
newArr.push(countries[i])
}
else{
continue
}
}
However, I am having a TypeError: Cannot read properties of undefined (reading 'endsWith)
out of index try this
for (let i = 0; i <= countries.length - 1; i++) {
console.log(countries[i]);
if (countries[i].endsWith("land") === true) {
newArr.push(countries[i]);
} else {
continue;
}
}
Don't use = because index will be one less than the array length!
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya'
]
newArr = [];
for (let i = 0; i < countries.length; i++){
console.log(countries[i])
if (countries[i].endsWith('land') === true){
newArr.push(countries[i])
}
else{
continue
}
}
Hope you have already got the answer from comments and other answers, but here is few improvement you can do using array reduce and &&
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya'
]
const z = countries.reduce((acc, curr) => {
curr.endsWith('land') && acc.push(curr);
return acc;
}, []);
console.log(z)