0

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; });
1
  • It stops when it hits the first element for sure. Hint: check what arr looks like after you sorted it. Commented Mar 28, 2017 at 2:18

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

That was it. I attached another function to sort the numbers in case the array receives numbers that are not in order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.