WOK
April 4, 2020, 9:44pm
1
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:
Learn to code. Build projects. Earn certifications.Since 2015, 40,000 graduates have gotten jobs at tech companies including Google, Apple, Amazon, and Microsoft.
ILM
April 4, 2020, 9:45pm
2
search about break
and continue
keywords, how they work with loops
1 Like
WOK
April 4, 2020, 9:57pm
3
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??
ILM
April 4, 2020, 10:13pm
4
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