Can someone please lend some clarity into part of this solution for me?
THE TASK : Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
The for loop returns the position of i. I thought that was enough to solve this challenge but no.
The ‘return arr.length’ is really confusing me here. It appears that return arr.length is returning the same value as the for loop, instead of returning the value of the length of the array.
Its like return arr.length is excluding all indexes greater than [i]. What am I missing?
function getIndexToIns(arr, num) {
arr.sort();
for (let i = 0; i < arr.length; i++) {
if (num <= arr[i])
return i;
}
return arr.length;
}
console.log(getIndexToIns([40, 60], 50));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0
Challenge: Basic Algorithm Scripting - Where do I Belong
hmm. I think you must be misunderstanding something…
Do you know how to use the console.log statement to log variables?
You can add a few of these in your code so you can review the procedure.
eg. console.log(i); but put it inside the if statement (you will need some braces first to do that)
Ok so now Im even more confused. console.log(i) inside of the if statement returned an unexpected value. And I still have no idea why return arr.length is returning the position of [i] instead of the length of the array.
Im not really sure where you’re going with this. Why would I need to change a passing solution? My question is about why the passing solution is correct as it makes no sense to me.
No. I did change .sort() to .sort((a, b) => a - b). Which allowed that last test to pass. So now Im just trying to understand why return arr.length is not returning what I expect.
It appears to be returning the index position of the num argument when inserted into arr argument. I would expect arr.length to return the length of arr instead.
This solution is returning 1, which is the index position of num after having been inserted into arr. But shouldn’t this solution be returning the length of arr, which would be 3?
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num)
return i;
}
return arr.length;
}
console.log(getIndexToIns([40, 60], 50));