function getIndexToIns(arr, num) {
// Find my place in this sorted array.
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
a= arr.sort(function(a,b){
return a-b;
});
console.log(arr);
var result;
for(var i=0;i<arr.length;i++){
if(a[i]>=num){
result=i;
break;
}
else if(i==(arr.length-1)&& a[i]<=num){
result=i;
}
}
return result;
}
getIndexToIns([5, 3, 20, 3], 5);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.
Number 1 is with the sorting function that you are using, note the following from MDN
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
That is why It’s better to go with the callback function of sort() method always and specify how you want your sorting to be done, for example to sort ascending you could use
arr.sort((a,b)=>{
return a-b;
})
read more about sorting with the callback function here:
The second problem that I see is with your comparison function and your if statement , you maybe overthinking it, if the number you are checking is less than or equal to the array element that it is being checked against, that is sufficient to break the loop and return the index. You don’t really need anything ‘else’ (pun intended)