Functional Programming - Sort an Array Alphabetically using the sort Method

THE TASK Use the sort method in the alphabeticalOrder function to sort the elements of arr in alphabetical order.

Im not understanding why this code isnt working. According to the examples provided, this code works just fine with numbers. Does it have something to do with there being 2 ‘a’ elements?

function alphabeticalOrder(arr) {
  // Only change code below this line

  return arr.sort(function(a, b) {
    return a - b;
  });

  // Only change code above this line
}

console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0

Challenge: Functional Programming - Sort an Array Alphabetically using the sort Method

Link to the challenge:

the objective of sort is to sort things based on some idea of their order. By default sort with no params will sort strings by their UTF-16 code values (in ascending order).
But in your case, you have made sort do some maths with the strings which maybe you thought about but in reality will cause the result to be NaN (not a number).

You can see this here (replace the numbers being subtracted with letters and then run the code to see that)
https://www.w3schools.com/js/tryit.asp?filename=tryjs_numbers_string3

What trolls?

When you call the sort method with a callback function, the function should return one of three values, indicating how to sort any two elements in the array:


compareFn(a, b) return value sort order
> 0 sort a after b
< 0 sort a before b
=== 0 keep original order of a and b

For numbers, sorting smallest to largest, this works very simply, because if a is larger than b, then a - b > 0, and so a will be sorted after b; and if a is smaller than b, then a - b < 0, and a will be sorted before b.

In the case of strings, you cannot simply subtract one from the other: "x" - "y" === NaN. You can still compare them with < and >, or you can convert them to UTF-16 code numbers with the charCodeAt method.

2 Likes

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