Frequent Line I See in Solutions

function(a, b){return a-b}

I see this used in many solutions and I don’t understand the importance of it. For example:

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

I understand that we are adding the num to the array, and then sorting the array. But what does the function inside the sort method actually do?

For this, I would recommend you take a look at the MDN or the devdocs.io page for the sort function. But here’s the gist.

Array.sort() takes a function, which it will use for sorting comparison. That function should return one of two values: a positive number or a negative number. If a negative value is returned, the first item will get a lower index value (will come first). If zero, they are equal by the comparison, and will remain unsorted. If greater than 0, then the second item being compared will get a lower index (will come first).

So, in the function

function(a, b){
  return a-b;
}

we’re assuming that we’re sorting a numeric list. If our list was [5, 2, 3, 8, 1], then the sort function would sort them based on that criteria. First, it would take 5 and 2, and return 5-2; (or return 3). As that is a positive value, the second (the 2) would be assigned a lower index.

That is grossly oversimplified, but that is the theory. There is a complex interaction between the various members of the array, far more than just “compare the zero-th index to the first index, then compare the first to the second, then…” But all we need to know is, when any pair of values are compared, they will be compared using the function we have specified.

That actually makes a lot of sense. I always understood (and used) .sort() alone without any functions. I thought it automatically sorted them from least to greatest without needing any additional parameters.

1 Like

the default sort behaviour is sorting using UTF-16 point code values, so you get a result of: [1, 10, 16, 2, 27, 4, 66] sorting these numbers

1 Like