Potential Solution for Where do I belong Challenge

I think I came up with a similar solution to solution 2 on this challenge, but I do sort the array in mine.

I may have just gotten away with something I shouldn’t have while sorting though, since I did not use a compareFunction with sort…but it appears to still work fine.

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

Can somebody clear up if this is a correct answer that could figure in the solutions or if I exploited something instead and why?

Thank you!

This line will not sort numbers. You can learn more about .sort here:

Other question, do you really need to sort numbers to decide the index of incoming number? If I take a queue ticket from the machine I don’t care the order of people in front of (and after) me, I only care how many them, right?

This challenge specifically asks for the array to be sorted:

You can imagine that array is sorted )) Challenge won’t be upset

Yeah I already looked at the specifications of .sort, but the code worked nonetheless. Can you explain why?

It both passed the challenge without any errors, and also upon checking what “arr.sort();” returned on the console log, it returned the original array in the correct order as intended.

If something works it might mean one of two things:

  1. All OK
  2. Tests are flawed
const arr = [414, 50, 9, 5, 12].sort();

console.log(arr); // [12, 414, 5, 50, 9]

By default sort method thinks of items as strings, like so: ['414', '50', '9', '5', '12'] and 414 goes before 5, as it starts with 4, just like dad would go before e.

Ohhh, ok that makes sense, I was using single digit numbers to test it so I didn’t realise! Thanks that cleared up the confusion for me.