Where do I belong - how can I stop the loop?

My loop continues till the end of the array. I want to stop it after the first result.

Your code so far


function getIndexToIns(arr, num) {
arr.sort(function(a, b){return a - b});
var ret = 0;

for (let i = 0; i < arr.length; i++){
  if((arr[i] - num) > 0 ){
    ret = i;
  }
  console.log(ret)
}
return ret;
}

getIndexToIns([10, 20, 30, 40, 50, 60, 70], 35);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36.

Challenge: Where do I Belong

Link to the challenge:

search about break and continue keywords, how they work with loops

1 Like

Thanks. It worked!! My final code below.

function getIndexToIns(arr, num) {
  arr.sort(function(a, b){return a - b});
  var ret = 0;
  for (let i = 0; i < arr.length; i++){
    if((arr[i] - num) >= 0 ){break;}
    ret = i + 1;
  }
  console.log(ret)
  return ret;
}

getIndexToIns([10, 20, 30, 40, 50], 35);


The if statement is to be true at i = 3. Why does it return i = 2 after the break??

if the if statement is true, ret is not changed
if the if statement is true at i=3 the last time that ret was changed is at i=2

:+1: :+1:
I understand now. Thanks