Arrays Iteration (forEach method)

Good day.

I have recently started learning about array iteration method. I was doing a challenge question and I cannot seem to understand why I cannot solve it. I don’t know where I’m going wrong (the output is displaying undefined. Please assist. I need your pearls of wisdom. The challenge is as follows:

/* Create a function that takes an array and a string as arguments
and returns the index of the string.*/
for example,
//findIndex([“hi”, “edabit”, “fgh”, “abc”], “fgh”) ➞ 2

My solution is as follows:

function findIndex(array,string){
let theIndex = arr.forEach( function(val,index){
return index;
} )
return theIndex

console.log(findIndex([“hi”, “edabit”, “fgh”, “abc”], “fgh”))

Hii, forEach method doesnt return a value, you need to assign theIndex var the value of Index inside the forEach like this:

arr.forEach(function(val,index)){ if(val===string){ theIndex = index } }

1 Like

You are my sunshine.I didn’t know that forEach doesn’t return a value. Thank you so much

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.