Tell us what’s happening:
I have completed this using for loop but can someone please help me understand whether or not I can do this using forEach and if so then how? I did attempt it and have commented the same!
Thanks for the help!
Cheers! Your code so far
function findElement(arr, func) {
// arr.forEach(function(item){
// if(func(item)){
// return item;
// }
// });
for(let i = 0; i < arr.length; i++){
if(func(arr[i])){
return arr[i];
}
}
}
// findElement([1, 2, 3, 4], num => num % 2 === 0);
findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0.
you can, but it is a bit difficult to do, and I don’t think it’s worth it, because you can’t just do a return inside forEach and stop everything, as the forEach callback is a different function.
You could do it using filter, totally possible implementation but a tad bit more resource intensive than the loop as you can’t stop looking at first found item.
There is probably an array method that could do this, but I don’t know it, you would need to do some research on your own
I will look into it! I am just trying to understand when and where - for and forEach are used. Sometimes I find that they are used interchangeably while in other cases, one or the other becomes wholly impractical.
Nevertheless, thank you for your assistance!
Appreciate it