# Basic Algorithm Scripting: Where do i Belong SOLUTION

Basic Algorithm Scripting: Where do i Belong SOLUTION
0

#1

I don’t understand why this doesn’t give the expected result.

``````function getIndexToIns(arr, num) {
let sortedArr = arr.sort();
for (let i = 0; i < arr.length; i++){
if (sortedArr[i] <= num) {
if (num <= sortedArr[i+1]) {
return i;
}
}
}
}

let res = getIndexToIns([10, 20, 30, 40, 60], 50);

console.log(res);
``````

#2

Two issues:

1. The default sort method will treat the numbers as strings, so after the default sort and array like the following:
``````[10, 20, 100]
``````

would become:

``````[10, 100, 20]
``````

Read the sort documentation here to see how you can sort numbers a specific way.

1. Once you resolve issue #1 above, then you still need to adjust your logic of your if statements. Use the following code which is everything after your sort line with console.log statements which I put in to allow you to see what is actually being compared in the following test case.
``````function getIndexToIns(arr, num) {
// assumes you have fixed your sorting issue
console.log('sortedArr = ' + JSON.stringify(sortedArr) + '\n');
for (let i = 0; i < arr.length; i++) {
console.log('Is ' + sortedArr[i] + ' is <= ' + num + '?');
if (sortedArr[i] <= num) {
console.log('  Yes.  Is ' + num + ' <= ' + sortedArr[i + 1] + '?');
if (num <= sortedArr[i + 1]) {
console.log('    Yes. Return i = ' + i)
return i;
}
}
console.log('-------------------------------')
}
}``````

#3

Thank you, will try to adjust accordingly.

#4

Can I also have some help with why my solution isn’t working? Here is my code, which works for half of the tests:

function getIndexToIns(arr, num) {
var counter = 0;
arr.sort(function(a, b){
return a-b;
})
for (var i = 0; i < arr.length; i++) {
if (num > arr[i]) {
counter += 1;
}
arr[counter] = num;
}
return counter;
}

getIndexToIns([40, 60], 50);