Comparing firsts letter of array elements(string) with another array element(letters)

currently working on one of the exercises on iteration, The .forEach() Method to be exact. the instruction was

Iterate over the fruits array to log I want to eat a plus the name of each fruit to the console. For example, I want to eat a mango .

You may use any form of callback you prefer.
i achieved this already…but because ‘I want to eat a apple’ isn’t grammatically correct, i decided to write a function that corrects this error.

//itearting through fruits my version
//defining the vowel array to compare our arrays with
const vowels=['a','e','i','o','u']

const food=['egg', 'orange','almond'];
const checkGrammer=x=>{
for(let q=0;q<fruits.length;q++){
  let m =0;
      console.log('I want to eat an ' + x[q])
    } else if (x[q][m]===vowels[1]){
      console.log('I want to eat an ' + x[q])
    } else if (x[q][m]===vowels[2]){
      console.log('I want to eat an ' + x[q])
    } else if (x[q][m]===vowels[3]){
      console.log('I want to eat an ' + x[q])
    } else if (x[q][m]===vowels[4]){
      console.log('I want to eat an ' + x[q])
    else {
      console.log('I want to eat a '+ x[q])

//mapping out the first letter of an element array

The new code worked as planned but gives error after my Output, can someone help me out please.
Below is the error report


TypeError: Cannot read property '0' of undefined
    at checkGrammer (/home/ccuser/workspace/javascript-iterators-for-each/main.js:16:12)
    at Object.<anonymous> (/home/ccuser/workspace/javascript-iterators-for-each/main.js:33:1)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)

Have you applied console.logs to see what is happening?

this is the complete output

Ah I see what is going on :wink: .

for(let q=0;q<fruits.length;q++)

Should be

for(let q=0;q<x.length;q++)

Your list of fruits is longer that your list of food :wink:
So what happens the moment it gets to an index position higher then the number of indexes in your food array, x[q][m] will return an undefined.

Happy coding!

1 Like

thanks a lot,I can’t still believe i didn’t see that.

1 Like

Sure anytime, no problem. Welcome to the world of debugging. Often the small mistakes do your head in :stuck_out_tongue:

Happy coding!

1 Like