Sorting through arrays in ascending order

I’m not sure why I’m not getting these letters to ascend in order. I’m using the sort method with the arrow function.

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

  return arr.sort((a,b) => a - b);
  
  


  // Only change code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

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

It would help to have a link to the challenge. Thanks.

Hey Jeremy I just updated and added a link to the challenge.

Ah, I see. Subtraction is not a properly defined operation between strings.

console.log("a" - "b");

Your callback function should return a number.

Do I need to convert the strings into numbers?

No. You can, but you would be recreating the default sorting callback function if you did so.

There is an example in the lesson on how to sort in reverse alphabetical order. If you want to use a callback function, I’d try to work through how that one works.

Or, you can build your own based upon these three rules for the callback function’s return value

  1. If the return value is 0, the two elements are the same/are equal

  2. If the return value is negative, then the first element comes before the second element

  3. If the return value is positive, then the second element comes before the first element

I’m getting undefined???



function alphabeticalOrder(arr) {
  // Only change code below this line
arr.sort((a,b)=>{
  if(a<b){
    return -1
  }else if (a>b){
    return 1
  }else{
    return 0
  }
});
  
}
  // Only change code above this line

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

Your function isn’t returning anything.

Isn’t the => a return from es6?

but do you return the sorted array itself? You return in the sort function, but you never return the array.

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