Where do I belong-Need Help

Where do I belong-Need Help
0.0 0

#1

I have created a logic of my own. My question is why result is returning -1. Whats wrong in my logic. I know problem is in indexOf line

Mycode so far

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var a;
  
  var sortedarr=arr.sort(function(a,b){
    return a-b;
  });
  
  var aftersort=sortedarr.map(function(val){
    return val-num;
  });
  
  var result=aftersort.indexOf(Math.min.apply(Math,a));
  
  return result;
}

getIndexToIns([3, 10, 5], 3);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/where-do-i-belong


#2

indexOf returns -1 when the item is not found.


#3

what modification i have to do in my code?


#4

Since you wrote the code, can you first help us understand why you wrote the following?

  var aftersort=sortedarr.map(function(val){
    return val-num;
  });

What are you thinking aftersort will contain after the above executes?


#5

Through this code, i am counting the difference between sorted array element(each element) and the number given(num). through this i think i can easily find the smallest difference and its index


#6

The following line references a variable a, but you have only declared it. Because it is never assigned a value, it is the value undefined by default. So, when you write: Math.min.apply(Math,a) you get Infinity.

var result=aftersort.indexOf(Math.min.apply(Math,a));

Basically, you are looking for the value Infinity in the array aftersort, which will always return false, so result will always be -1.


#7

Great. Thanks randelldawson
I need your advice. What should i do in above code to give me exact answer. Because i am stuck in my logic


#8

My suggestion is to rethink your algorithm. You should first write out your algorithm in plain language which should be a series of steps it would take to get the correct result. Then, walk through your steps with each test case to make sure your logic is correct before trying to write your code.


#9

Great suggestion. Thanks once again