I think you might be making the solution more complicated than it needs to be. One of the first things you do is sort the array passed into the function. (By the way, you shouldn’t rely on the default sort but rather explicitly tell sort you want to sort by number. Look up on google how to do that). Assuming you do have the array sorted numerically in ascending order, for example [10, 20, 30, 40, 50] and I gave you the number 35, tell us how you would figure out where to put 35 in that array in plain English, no code. Just describe the process in your mind of how you would do it.
Firstly, getIndexToIns doesn’t have a return value so it always returns undefined.
Second, you have the value 50 hardcoded into the solution, which wouldn’t work for other cases even if the logic was correct.
Let’s run through the code using the example getIndexToIns([40, 60], 50):
Pass [40, 60] as arr and 50 as num.
Create h, an empty array.
arr gets sorted into [40, 60].
Start for loop: i = 0; i < 2; i++
Push 40 into h → [40]
if(40 < 50) evaluates to true
Push 50 into h → [40, 50]
for loop: i = 1; i < 2
Push 60 into h → [40, 50, 60]
if(60 < 50) evaluates to false
end for loop
Call findIndex on h → [40, 50, 60], calling number on every element.
40 == 50 → false
50 == 50 → true
h.findIndex returns 1.
That’s the right answer for this case, so why doesn’t it work for others? Take bbsmooth’s example with [10, 20, 30, 40, 50] and 35.
If we run through the for loop, 35 gets inserted right from the get-go because 10 is less than 35. Then, it happens again for 20 and 30 so our final array is [10, 35, 20, 35, 30, 35, 40, 50]!
The first occurrence of 35 is at index 1, so your function would return 1.
Whenever you find yourself struggling, break down your code like that and you can find exactly where things start going wrong; in this case, the if condition (arr[i] < num).
This is also why it helps to keep things simple so you can debug more quickly. There are faster ways of solving this problem that don’t involve using .push() to build a new array from scratch. I recommend reading further into array functions.