w3resource

JavaScript Sorting Algorithm: Alphabetically sorts the characters in a string

JavaScript Sorting Algorithm: Exercise-19 with Solution

Write a JavaScript program to sort the characters in a string alphabetically.

  • Use the spread operator (...), Array.prototype.sort() and String.prototype.localeCompare() to sort the characters in str.
  • Recombine using String.prototype.join('').

Sample Solution:

JavaScript Code:

const sortCharactersInString = str =>
  [...str].sort((a, b) => a.localeCompare(b)).join('');
 
console.log(sortCharactersInString('cabbage'));

Sample Output:

aabbceg

Flowchart:

JavaScript Searching and Sorting Algorithm Exercises: Alphabetically sorts the characters in a string.

Live Demo:

See the Pen javascript-common-editor by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to sort an array of objects, ordered by a property, based on the array of orders provided.
Next: Write a JavaScript program to find the lowest index at which a value should be inserted into an array in order to maintain its sorting order, based on the provided iterator function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-19.php