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?

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?

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

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.

3 Likes

Great suggestion. Thanks once again

1 Like

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