1

I would like to write a shorter code for find by using .forEach but I found problems with the counting and return does not work:

function find(array, element) {
 array.forEach((_, i) => {
  if (array[i] === element) {
    return i;
  }
 })
 return "Not found";  
}

let array = [2,3,5,7,11];


function find(array, element) {
  for (let i = 0; i < array.length; i++) {
    console.log(i)
    if (array[i] === element) {
      return i;
    }
  }
  return "Not found";
}

console.log(find(array, 5)) //2
console.log(find(array, 12)) //Not found
Matteo
  • 79
  • 8
  • 1
    You are returning to the caller of the callback function, and not your actual `find()` function call. Returning from `.forEach()` doesn't do much except for terminating that particular iteration that you're on. – Nick Parsons Oct 05 '21 at 08:09
  • Just making sure you are aware that [Array.prototype.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) exists? – Jesper Oct 05 '21 at 08:10
  • 1
    @Jesper more like [Array.prototype.indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexof) as the goal here is to get the index of the element – Krzysztof Krzeszewski Oct 05 '21 at 08:11
  • 1
    In your `forEach` the `_` is equal to `array[i]`. – Wais Kamal Oct 05 '21 at 08:15
  • Here's a fixed version: https://jsfiddle.net/qt1Lvdsk/ (also, did you mean "refactoring"?) –  Oct 05 '21 at 08:19
  • Write better code, not "shorter" code. `forEach` is the wrong tool here. – Bergi Oct 05 '21 at 09:16

2 Answers2

1

let array = [2,3,5,7,11];

function find(array, element) {

let index =  array.indexOf(element) != -1 ? array.indexOf(element) : "Not Found";  

return index;

}

console.log(find(array, 5))

console.log(find(array, 12))

Ravi Kumar
  • 11
  • 1
1

return is not going to work inside a forEach I suggest you use the filter function instead. but if you insist on using forEach you can use this code as a sample.

function find(array, element) {
let result="not found";
 array.forEach((arrayItem, i) => {
  if (arrayItem === element) {
    result = i;
  }
 })
 return result;  
}
  • 1
    It would be a good idea to declare `let result = 'Not found';` in case the entry number is not in the array. So it would return `Not found` instead of `undefined` – Gass Oct 05 '21 at 09:33