I completed this challenge successfully, so I’m not asking for anyone to solve it for me. However, my code seems kind of verbose and inefficient, so I am looking for examples of how others solved it, so I can learn from them.
Here is my code:
function getIndexToIns(arr, num) {
var diff = 0;
var minDiff = 0;
var insPos = 0;
function sortNumber(a,b) {
return a - b;
}
arr.sort(sortNumber);
for(var i = 0; i < arr.length; i++){
diff = num - arr[i];
if(i === 0 || (diff < minDiff && diff >= 0)){
minDiff = diff;
if(arr[i] == num){
insPos = i;
}
else{
insPos = i + 1;
}
}
}
return insPos;
}
Hi what you did is sort out the array and then more or less sorted it again with the num and got the position of the num … other way would be to arr.push(num) … this adds the num to the array … then run your arr.sort(sortNumber) … as now you have all the numbers sorted . then just …
return arr.indexOf(num) …
@P1xt, thanks for this very insightful post. This is exactly the type of input I was hoping to receive. I am trying to become a better programmer in the sense of solving problems more elegantly and efficiently. You’ve done a great job here.
Hi all. I am new to JS. This is my first post. And this is my solution.
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr.push(num);
arr.sort(function(a,b){
return a-b;
});
return arr.indexOf(num);
}