Roger
Roger

Reputation: 597

Loop won't break in javascript

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; });

Upvotes: 0

Views: 144

Answers (2)

134
134

Reputation: 28

Please remove arr.sort() your function works find please find the updated code .its working fine run and check.

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;
}

console.log(findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; }));

Upvotes: 1

ffflabs
ffflabs

Reputation: 17481

I believe your for over array is off.

Instead of

for(var i = arr[0]; i <= arr[arr.length-1]; i++) {

It should be

for(var i = 0; i <= arr.length-1; i++) {

Otherwise, you might as well be verifying undefined array indexes.

Upvotes: 2

Related Questions