DEV Community

Randy Rivera
Randy Rivera

Posted on

2 1

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.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Billboard image

Try REST API Generation for MS SQL Server.

DreamFactory generates live REST APIs from database schemas with standardized endpoints for tables, views, and procedures in OpenAPI format. We support on-prem deployment with firewall security and include RBAC for secure, granular security controls.

See more!

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay