DEV Community

Randy Rivera
Randy Rivera

Posted on

Sorting an Array Alphabetically using the sort Method

  • The sort method sorts the elements of an array according to the callback function.

  • For example:

function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}
ascendingOrder([1, 5, 2, 3, 4]); // This would return the value [1, 2, 3, 4, 5].
Enter fullscreen mode Exit fullscreen mode
function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? 1 : -1;
  });
}
reverseAlpha(['l', 'h', 'z', 'b', 's']);
// This would return the value ['z', 's', 'l', 'h', 'b'].
Enter fullscreen mode Exit fullscreen mode
  • Let's use the sort method in the alphabeticalOrder function to sort the elements of arr in alphabetical order.
function alphabeticalOrder(arr) {
  // Only change code below this line

  // Only change code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));
Enter fullscreen mode Exit fullscreen mode
  • Answer:
function alphabeticalOrder(arr) {
let sortArr = arr.sort();
return sortArr;

}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));
// alphabeticalOrder(["a", "d", "c", "a", "z", "g"]) would return [ 'a', 'a', 'c', 'd', 'g', 'z' ]
Enter fullscreen mode Exit fullscreen mode
  • OR:
function alphabeticalOrder(arr) {
  return arr.sort((a, b) => {
    return a === b ? 0 : a > b ? 1 : -1; // <-- a less than b

 });
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));
Enter fullscreen mode Exit fullscreen mode

Larson, Quincy, editor. “Sort an Array Alphabetically using the sort Method.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.

Top comments (0)