Basic Algorithm Scripting - Where do I Belong

I googled a solution for the lesson but i am trying to understand the code written below
Describe your issue in detail here.

function getIndexToIns(arr, num) {
    var i;
    arr.sort(function(a, b){
        return a - b;
    });
    for (i = 0; i < arr.length; i++) {
        if (arr[i] > num) {
            return i;
        }
    }
    return arr.length;
}

console.log(getIndexToIns([10, 20, 30, 40, 50], 35)); // 3
console.log(getIndexToIns([1, 2, 3, 4], 1.5));        // 1
console.log(getIndexToIns([20, 3, 5], 19));           // 2
console.log(getIndexToIns([4, 3, 2, 1], 5));          // 4`
function getIndexToIns(arr, num) {
  return num;
}

getIndexToIns([40, 60], 50);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:107.0) Gecko/20100101 Firefox/107.0

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

my questionis what does the parameters a and b represent inside the sort function?

Have you looked up the sort function? Searching “MDN sort javascript” gives me

ok looked it over i just dont understand return a-b. does that mean that it is returning the difference of the two parameters?

Yes. And what does this part say that the return value means?

(Specifically you want the table)

Yes, look at the table.

a - b returns the difference, but the specific amount doesn’t matter, only whether that value is positive, negative, or zero.

If a - b returns a negative value, then it logically means that a is a smaller number than b, so their order remains unchanged [smaller value should come first].

If a - b returns a positive value, then it logically means that a is a larger number than b, so their order is switched [larger value should come second].

If a - b returns zero, then they are left alone, as it doesn’t matter which one comes first.

The sort() function iterates over all the indexes of the array, two items at a time, and switches their order by using the returned value [positive, negative, or zero] to determine whether a or b is the larger value. It switches them only if a - b returns a positive value.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.