Where do I belong - doesn't work only for one case

This code works for all cases but one.

I don’t understand why it isn’t workingc:frowning:
please help

function getIndexToIns(arr, num) {
  var ptr=0;
while(ptr<arr.length )
        return ptr;      
  return ptr;
getIndexToIns([5, 3, 20, 3], 5);

The problem is that arr.sort() isn’t doing what you think it is doing. This is a pretty nasty thing to happen to a beginner.

Let me quote from w3schools: https://www.w3schools.com/jsref/jsref_sort.asp

By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings (“Apple” comes before “Banana”). However, if numbers are sorted as strings, “25” is bigger than “100”, because “2” is bigger than “1”.
Because of this, the sort() method will produce an incorrect result when sorting numbers.
You can fix this by providing a “compare function”

The first argument to the sort can be a function to compare two elements which will fix the problem.

1 Like

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a 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.


1 Like