Hello, I am trying to practice Higher Order Functions and Iterators and my code keeps returning undefined and I can’t figure out what I’m doing wrong.
const persons121 = [
‘Oliver’, ‘Lorenzo’, ‘Micaela’, ‘Rosario’, ‘Clara’
];
const namesWithVowel = (array121) => {
let result = array121.forEach(name => {
return name[0] === ‘O’;
});
console.log(result);
}
let doesBeginWithVowel = function(func, array) {
let check = func(array);
console.log(In the list ${check} is the name that begins with a vowel
);
}
doesBeginWithVowel(namesWithVowel, persons121);
// my code returns the following:
In the list undefined is the name that begins with a vowel
I would be very grateful if someone can help me out. I apologize if I have missed something obvious. Many thanks.
mtf
December 28, 2022, 2:54pm
2
What is the first thing we learned about, Array.forEach()
?
Yes you’re right, it returns undefined… but even so if I use a different iterator it also returns undefined.
mtf
December 28, 2022, 3:05pm
4
Then we need to rethink the problem. The lower part of your code invokes a higher order function that takes two arguments. A function, and an array of string data. What is it meant to return? An array of strings that begin with a vowel. One of the iterators we learned about is aptly suited to this task; which is it?
1 Like
I think it is .map() — but that also returns undefined… i must be missing something
mtf
December 28, 2022, 3:15pm
6
.map()
can be used as a conditional iterator, but it returns an array the same size as the original. You’re getting warmer.
1 Like
I am back with forEach()… unless I use findIndex() to locate the index and then log the word with the matching index.
mtf
December 28, 2022, 3:31pm
8
Now you’re getting colder.
filter() — returns an array containing the matching results.
1 Like
If I call the namesWithVowel(persons121) then it logs [‘Oliver’]
So that function is working…
However when I call the higher order functon:
doesBeginWithVowel(namesWithVowel, array121)
then I get undefined… so the problem must be here
I figured it out… thank you for pointing me in the right direction.
Here is the code that works:
const persons121 = [
‘Oliver’, ‘Olivia’, ‘Lorenzo’, ‘Micaela’, ‘Rosario’, ‘Clara’
];
const namesWithVowel = (array121) => {
let result = array121.filter(name => {
return name[0] === ‘O’;
});
return result.join(", ");
}
let doesBeginWithVowel = (funct, array543) => {
console.log(The names ${funct(array543)} in the list begin with vowels
);
};
doesBeginWithVowel(namesWithVowel, persons121);
// it returns — The names Oliver, Olivia in the list begin with vowels
1 Like