I’ll give you a hint. You are making this much more complicated than it needs to be. That’s why I asked you to explain in plain language (no code) how you would find the lowest index to insert num. The first step to coding an algorithm is to know how the algorithm works. I’m hoping that by talking it out you will come to see how simple this really is.
function getIndexToIns(arr, num) {
// sorting the array
for(let i = 0; i<arr.length ; i++){
for(let j=0;j<arr.length;j++){
if (arr[j]> arr[j+1]){
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp ;
}
}
}
for(let i=0;i<arr.length;i++){
//when num<arr[0] insert num at first index
if(num < arr[0]){
arr.splice(0,0,num)
return arr.indexOf(num);
}
// if arr[before] less than num and
// arr[after] greater than num than insert between them
else if(arr[i]<num && arr[i+1]>num){
arr.splice(i+1,0,num)
return arr.indexOf(num);
}else if(num > arr[arr.length-1]){
// otherwise if num is greater than last index num insert at last position
arr.splice(arr.length,0,num)
return arr.indexOf(num);
}
}
return arr.length && num;
}
console.log(getIndexToIns([40, 60], 50));
I’m not convinced you have a good idea of how to solve this yet. And I’m not sure why you are inserting things into the array. Please think this through a little more. You are sorting the array correctly. Once you have a sorted array, how would you figure out where a new number would fit in to keep it sorted. You don’t actually have to insert the number into the array to get the answer. You just need to know where to insert it.
I get that talking about code can be intimidating, but it really is important. It is difficult to debug code if you can’t provide a description in simple words of what you are trying to do. These problems aren’t about guessing the right syntax. These problems are about describing a process to solve a problem.