So I am trying to create a function where it will display to me the FIRST even number divisible by 2. The values to be divided are inside an array and another function helps me determine whether the values in the array are divisible by 2. The problem is that the loop won't break and the loop continues until the last value of the array. I want it to break once it finds the first number divisible by 2. So in this case the loop should stop once it reaches value 8 in the array but it doesn't and continues until 10. I hope you can help me
This is my code:
function findElement(arr, func) {
var num = 0;
arr.sort();
for(var i = arr[0]; i <= arr[arr.length-1]; i++) {
if(func(arr[i])) {
num = arr[i];
break;
}
if(!func(arr[i])) {
num = undefined;
}
}
return num;
}
findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; });
arrlooks like after you sorted it.