Where do I belong-Need Help

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

indexOf returns -1 when the item is not found.

what modification i have to do in my code?

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

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.

1 Like

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

Great suggestion. Thanks once again

1 Like

My code

Spoiler

function getIndexToIns(arr, num) {

  return (arr.filter(x=>x<num)).length;
   }
getIndexToIns([40, 60], 50);

3 Likes

Oooooh… Damn! That’s slick. Totally forgot about boolean expressions and filter().Here’s what I did:

Summary

This text will be hidden

function getIndexToIns(arr, num) {
    let index = 0;
    arr.sort((h,j) => h-j);
    while (arr[index] < num) {
        index++;
    }
    return index;
}

2 Likes