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

Very helpful answer.
Thank you, will try to adjust accordingly.