Can someone explain why we return arr.length at the end of this code challenge? I understand returning the index, but in order to complete the challenge I had to insert “return arr.length” which I found in the “get help” for this challenge.
Apologies, I thought this was linked to the challenge and solution in question.
Here is the solution answer provided:
function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num)
return i;
}
return arr.length;
}
Here was my code:
function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b)
let index = 0;
for (let i = 0; i < arr.length; i++) {
if (num <= arr[i]){
index = i
}
}
return index
}
When my attempt wouldn’t work, I just tried returning i. Eventually I had to look at the answer to pass. And I was having a hard time understanding why arr.length had to be returned.
function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num)
return i;
}
return arr.length;
}
the for loop will iterate through the array and compare each value with number to insert, and if find any value greater than or equal to the number to insert we insert at that position.
[1,2,3,4,5,6,7] insert 5
first compare 5 with 1 condition false
and 2 flase
3 false …
5 true . so insert at that position
now consider this scenario
[1,2,3,4,5,6,7] insert 9
first compare 5 with 1 condition false
and 2 flase
3 false …
7 false
we finished the iteration and the condition is not true for any of the elements. which means all the elements in the array is less than the number to insert. so the position of insertion is simply the last index which is equal to array.length, so just retun that. thats it
Thank you for that explanation! I think I understand it now. The code is returning the index in which the element is inserted and breaking out of the loop, meaning that the arr.length is going to equal the index in which the element is inserted.