"Where do I belong" algorithm

Hi Everyone,

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.

@P1xt Thanks for the advice. I will do my best to put it into practice.

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);

}

Mine was identical to ddamajas.

Got most of it from reading the documentation.

My solution was quite simple, although it used an additional array method.

function getIndexToIns(arr, num) {
  arr.push(num);
  var sortedArray = arr.sort(function(a,b){return a-b;});
   function indexer(element) {
		return element == num;
   }
return sortedArray.findIndex(indexer);
}

Hi @dpberry552 here is how I solved. I believe it’s an elegant way to approach .

function getIndexToIns(arr, num) {
// Find my place in this sorted array.
arr.push(num);
arr = arr.sort(function(a,b) {
return a-b;
});

num = arr.indexOf(num);

return num;
}