I was working on this puzzle, and I got a working solution for almost all cases:

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

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

I got a bit fed up, so I checked the solution: I see that, to deal with the other scenarios, the proposed solution returns “arr.length”. I don´t understand why, though. Could anyone explain?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.