What's the subtraction doing in this sort function?

I understand that the .sort function will sort from smallest to biggest.

But what is the a - b part actually doing?

If I remove or change it, the array no longer gets sorted.

I’ve tried adding in some logging to see what’s going on, but I don’t actually see a being reduced by b at any point?

Is there something more complex going on under the hood here?

function getIndexToIns(arr) {

  const value = arr.sort((a, b) => {

    console.log("a is " + a)

    console.log("b is " + b)

    return a - b});

    console.log(value)

}

getIndexToIns([10, 20, 30, 50, 40]);

It is generating a positive or negative number so the method knows how to sort those elements.

When in doubt, check the documentation. Google “mdn array sort”.

Professional developers google stuff all the time, too many details to memorize.

Ah, reading this I think I understand why we do it as an arrow function.

Is it to ensure it is treated as a number and not a string? Like, specifically telling the function what data type they are?

Ah, reading this I think I understand why we do it as an arrow function.

Is it to ensure it is treated as a number and not a string?

We are giving it a callback function because by default sort will convert to a string and sort alphabetically. That won’t work the way we want with numbers (10 would be less than 2). So, unless we wan’t an alphabetical sort, we must give it a callback.

Just to be clear, it doesn’t have to be an “arrow” function, that’s just quick and convenient. But any of the three ways to define a function in JS will work:

const sorter1 = (a, b) => a - b
function sorter2(a, b) { return a - b }
const sorter3 = function(a, b) { return a - b }

console.log([3, 1, 2, 4, 5].sort(sorter1))
// [1, 2, 3, 4, 5]

console.log([3, 1, 2, 4, 5].sort(sorter2))
// [1, 2, 3, 4, 5]

console.log([3, 1, 2, 4, 5].sort(sorter3))
// [1, 2, 3, 4, 5]
1 Like

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