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