Index of an element in an array

Task

Provided is a function find which accepts two parameters in the following order: array, element

return the index of the element if found and "Not found" otherwise. You may assume that all array elements are unique.

This is what I have so far:

function find(array, element) {
  
  array.forEach(function(n){ 
    if (n === element) return array.indexOf(n);
  });
  
  return "Not found"
}

However, it is not passing the task when I run it on the website this problem is from. Any guidance would be appreciated.

Hi,

What lesson is this, it’d help if you include it also, so we don’t waste time looking for it :slightly_smiling_face:

  1. You can’t return out of a forEach, it will keep going.

  2. You don’t need a loop you can just use the indexOf() method.

function find(array, element) {  
  if(array.indexOf(element) !== -1) {
    return array.indexOf(element);
  }
  
  return "Not found"
}

Like lasjorg said, and quoted from MDN:

forEach () executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

Others already mentioned some stuff, but if you really want to use forEach here, you need to know that this method can actually pass 2 arguments to your function, not just one, with second argument storing current element index like this:

array.forEach(function(n,index){ 
    if (n === element) console.log(index);
  });

I will leave rest to your imagination.

This is the link to the challenge

I have now solved it using:

function find(array, element) {  
 
   return array.includes(element) ? array.indexOf(element) : "Not found";

}

Alternative:

function find(array, element) {  
 
   return array.indexOf(element) > -1 ? array.indexOf(element) : "Not found";

}

This is bad solution because it executes method “indexOf” twice, basically making search twice for same thing.
Consider this comparison:

find is your function. find2 is same function, but instead of running indexOf twice, it stores result and then uses it.
You will see that this approach will be reliably faster.
In other words, if you are executing some calculating function once, and need to use result in multiple areas, just store result in variable, do not re execute function for no reason.