Where do I belong - Help

Hello,

I’ve try to solve this challenge like this

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.sort();
  
  for (i = 0; i < arr.length; i++) {
    if (arr[i] <= num <= arr[i + 1]) {
       return(arr.indexOf(arr[i]));     
    }
  } 
}

For an unknow reason to me it didn’t work but I think the logic should work right ?

I’ve check the hint and found that logic even more clear, I managed to redo it by myself but I would still like to understand why the first code didn’t work

  arr.sort();
  
  var final = 0;
  for (i = 0; i < arr.length; i++) {
    if (num > arr[i]) {
      final += 1;
    }
  }
  return final;
}

On first inspection:

Sort doesn’t sort numerically - It sorts by Unicode points.

In order to get it to sort the way you want, you need a function inside of the sort method. Something like this:

arr.sort(function(a, b) {
return a-b;
}

(Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
You may also need to store that in a new array. I can’t remember. But yeah that should help.

1 Like

Er. forgot a parenthesis.

arr.sort(function(a, b) {
return a-b;
});

1 Like

That is the reason why first code works incorrect:

JavaScript interpretator reads this expression not same as human, you need to rewrite as 2 statements (a <= b) && (b <=c), the (a<=b<=c) not allowed (that would work eg. in Python but not here in JavaScript)

UPD And how zealousAnemone said, maybe it sorts incorrect - try to console.log(arr.sort()) to see if there is a problem here

1 Like

Thanks a lot zealousAnemone, keith1111 and randelldawson, I’m going to test with thoses changes

I’m starting to think that freecodecamp challenges are not enough, there are things that I use without fully understanding how they work. Did you experience the same feeling ? Do you advise specific sources to fill the gap ?