Functional Programming - Sort an Array Alphabetically using the sort Method

Tell us what’s happening:
Describe your issue in detail here.

Your code so far
Hey all…this challenge seems to be easy and i cant find my mistake…kindly someone to tell me whats wrong with my code. Thanks.

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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

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

Link to the challenge:

Can you explain why you decided to use this code here?

(Does subtracting letters help to sort them?)

The thing about sort is all it really cares about with its callback is if the value it returns is 0, less than 0 (-1), or greater then zero (1), and based on that it will move the items in a or b to there appropriate spots. Here you are using the minus (-) with a and b, and a and b are strings. What is 'a'-'b' going to get you in Javascript? The other example code is more what you want, but it can look very confusing if your new to coding with its two ternary operators.

Why not take a look and see what the sort method does by default?

To return the strings in an ascending order

Do you still believe that subtracting letters will help to sort them though? (Or have you had a chance to rethink that?)

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