Sort an Array Alphabetically using the sort Method - what does the return statements in sort method signify

Tell us what’s happening:
Can anyone explain what’s happening in these two blocks of code. I didn’t understand how return a-b is arranging numbers into ascending order and what is happening when we are passing an array of strings (or characters).


function alphabeticalOrder(arr) {
  // Add your code below this line
 return arr.sort(function(a,b)
  {
    return a>b;
    });
  
  // Add your code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

AND


function alphabeticalOrder(arr) {
  // Add your code below this line
 return arr.sort(function(a,b)
  {
    return a-b;
    });
  
  // Add your code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method

Hi @anotherwebguy,
Sort is expecting the anonymous comparing function to return one of three options. a negative number, zero, or a positive number. And depending on what number you pass will determine how item a and item b relate to each other in the sorted array.

The first compare function is returning a boolean (is a greater than b). Javascript does something called type conversion which will try to interpret the your code using the proper types. For instance:

console.log(1 + '1') // '11' as a string

Because sort is expecting the return value to be a number. Type conversion happens where:

true == 1
false == 0

I partially understood the concept of the compare function for numeric sorting. When I write return a-b and pass [10,5] in the sort method, then it returns 10-5 = 5(a positive value) and places 10 as a value higher than 5 (correct me, if I went wrong anywhere).

But I still didn’t understand what is happening when I write return a>b in the compare function, and how alphabetic sorting is taking place.

Good question. Looking into the mdn docs this is what it says about sort returning 0 and 1.

  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to an index lower than a, i.e. b comes first.

So in your example using [10, 5] if you are returning the boolean value a > b it compares 10 > 5. Due to type conversion, sort interprets the return value true as 1, and therefore sorts b at a lower index e.g [5, 10].

There are some detailed docs there about how sort deals with strings based on unicode if you’re interested.

1 Like