Emmanuel Akinfulubi

JavaScriptFunction

Sort the letters of a string alphabetically in JavaScript

Beginner · 4 min read

Sorting the letters of a word puts them in alphabetical order: 'webmaster' becomes 'abeemrstw'. It sounds like a toy, but it is the trick behind anagram checks. Two words are anagrams, like listen and silent, exactly when their sorted letters match.

In this tutorial you will write sortLetters, a one-line function that sorts the letters of a string. Then you will see two surprises: how capital letters sort, and why the usual split('') can break emoji. You need to know what an array is and what a function is.

Strings can't sort, arrays can

Arrays have a sort() method. Strings don't, so the plan is the same one you use for reversing:

  1. Turn the string into an array of characters.
  2. Sort the array.
  3. Join the characters back into a string.

How sort() decides the order

With nothing inside the brackets, sort() compares items as text, by their character codes. Every character has a code number. Small letters run from a (97) to z (122), and capitals from A (65) to Z (90). charCodeAt shows you the code:

JavaScript

console.log('a'.charCodeAt(0)); // 97
console.log('A'.charCodeAt(0)); // 65
console.log(['c', 'a', 'b'].sort()); // [ 'a', 'b', 'c' ]

For a word that is all small letters, that is plain alphabetical order. Keep the capitals in mind; they come back in Step 3.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

4 Sort a string’s letters

easy

'webmaster' should give 'abeemrstw'. Assume no punctuation or digits.

Stuck? Three hints, smallest first
  1. 1. Spread into characters, sort(), then join.
  2. 2. split(‘’) breaks characters outside the basic range in half; [...text] does not.
  3. 3. Default sort() compares by code unit, so every capital sorts before every lower-case letter.

Step 1: spread, sort, join

[...text] spreads a string into an array of its characters. Then sort() and join('') finish the job:

Step 1

const sortLetters = (text) => [...text].sort().join('');
console.log(sortLetters('webmaster')); // 'abeemrstw'
console.log(sortLetters('cba'));       // 'abc'
console.log(sortLetters(''));          // ''

That matches the exercise. Repeated letters, like the two es, are all kept, so the result always has the same length as the input.

Step 2: why not split('')?

Many answers use text.split('') instead of [...text]. For plain letters the two give the same array. The difference shows with an emoji:

Step 2

const emoji = 'b\u{1F600}a';
console.log([...emoji].length);      // 3
console.log(emoji.split('').length); // 4

\u{1F600} is the grinning face emoji, written as a code so the snippet is easy to copy. Inside JavaScript, a string is stored as small pieces called code units. Ordinary letters take one each. This emoji takes two. split('') cuts between code units, so it cuts the emoji into two halves. [...text] walks through real characters and keeps it whole.

For reversing, broken halves end up swapped. For sorting it is worse: the two halves are sorted separately, they can end up apart, and the emoji is destroyed. So use [...text].

Step 3: capitals sort first

Try a word with capitals:

Step 3

console.log(sortLetters('WebMaster')); // 'MWabeerst'

M and W jumped to the front. Their codes (77 and 87) are lower than any small letter, so the default sort puts every capital before every small letter. That is "code order", not what a person means by alphabetical.

Step 4: sort like a person would

To sort the way a dictionary does, pass sort a compare function. It receives two items, a and b, and returns a negative number if a should come first, a positive number if b should, or 0 if they are equal. localeCompare does exactly that for text:

Step 4

console.log('a'.localeCompare('b', 'en')); // -1
const sortLettersAlphabetically = (text) =>
  [...text].sort((a, b) => a.localeCompare(b, 'en')).join('');
console.log(sortLettersAlphabetically('WebMaster')); // 'abeeMrstW'

The 'en' tells it to use English rules. Always pass a language: without one, the result depends on the settings of the computer the code runs on.

Now M sits between e and r, and W comes last, the way you would expect. For the exercise's all-lowercase 'webmaster', both versions give the same answer.

The full solution

The panel has sortLetters and sortLettersAlphabetically. It prints 'webmaster' sorted, the capital-letter case both ways, and then the emoji example sorted with spread and with split(''), so you can see the broken version. Press Run to compare.

The answer

const sortLetters = (text) => [...text].sort().join('');

// Case-insensitive, and locale-aware, which is usually what a person expects.
const sortLettersAlphabetically = (text) =>
  [...text].sort((a, b) => a.localeCompare(b, 'en')).join('');

console.log("sortLetters('webmaster')  =", sortLetters('webmaster'));
console.log('the expected value        =  abeemrstw');
console.log("sortLetters('WebMaster')  =", sortLetters('WebMaster'), '<- capitals first');
console.log('alphabetical instead      =', sortLettersAlphabetically('WebMaster'));
console.log('--- why split("") is the wrong tool ---');
const emoji = 'b\u{1F600}a';
console.log("[...text] length :", [...emoji].length);
console.log("split('') length :", emoji.split('').length, '<- the emoji became two halves');
console.log('sorted with spread:', JSON.stringify([...emoji].sort().join('')));
console.log("sorted with split :", JSON.stringify(emoji.split('').sort().join('')), '<- halves separated, now broken');

Output


      
18 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 18 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

18 checks

test("the example in the question", sortLetters('webmaster'), 'abeemrstw');
test('a single letter', sortLetters('a'), 'a');
test('an empty string', sortLetters(''), '');
test('already sorted stays put', sortLetters('abc'), 'abc');
test('reversed gets fixed', sortLetters('cba'), 'abc');
test('repeated letters are all kept', sortLetters('aab'), 'aab');
test('the length never changes', sortLetters('webmaster').length, 'webmaster'.length);
test('and the same letters come back', sortLetters('webmaster').split('').sort().join(''), 'webmaster'.split('').sort().join(''));
test('capitals sort before lower case by code unit', sortLetters('bA'), 'Ab');
test('while the locale sort groups them', sortLettersAlphabetically('bA'), 'Ab');
test('and orders a mixed word alphabetically', sortLettersAlphabetically('WebMaster'), 'abeeMrstW');
test('spreading gives three characters', [...'b\u{1F600}a'].length, 3);
test('while split("") gives four pieces', 'b\u{1F600}a'.split('').length, 4);
test('because the emoji was cut into two halves', 'b\u{1F600}a'.split('')[1].codePointAt(0) >= 0xD800, true);
test('each half is a lone surrogate, not a character', 'b\u{1F600}a'.split('')[1].codePointAt(0) <= 0xDFFF, true);
test('spreading produces no lone surrogates', [...'b\u{1F600}a'].every((c) => c.codePointAt(0) < 0xD800 || c.codePointAt(0) > 0xDFFF), true);
test('so the sorted result has the right number of characters', [...[...'b\u{1F600}a'].sort().join('')].length, 3);
test('whereas the split version silently has four', ['b\u{1F600}a'.split('').sort().join('')].map((r) => r.length)[0], 4);

[...text] rather than text.split('') is the habit worth forming. split('') cuts by UTF-16 code unit, so a character outside the basic range is torn into two halves — and once you sort, those halves end up in different places and the character is destroyed. The assertions check an emoji surviving one and not the other.

The other half is what "alphabetical" means. Default sort() compares code units, so 'bA' becomes 'Ab' because A is 65 and b is 98. That happens to match the expected output for 'webmaster', which is all lower case. For mixed case you almost certainly want localeCompare with an explicit locale — and the locale is not optional, or the result depends on the machine.

Common mistakes

  • Calling 'webmaster'.sort(). Strings have no sort method, so you get a TypeError. Go through an array.
  • Forgetting join(''). You get an array back. And join() with nothing in the brackets puts commas between the letters.
  • Trusting the default sort for mixed case. It puts all capitals first. Use localeCompare with a language when people will read the result.

Try it yourself

  1. Write isAnagram(a, b) that returns true when sortLetters(a) === sortLetters(b). Test 'listen' and 'silent'.
  2. Sort the letters in reverse order, from z to a. (Hint: add .reverse() before join.)
  3. Make isAnagram ignore capitals and spaces, so 'Dormitory' and 'dirty room' count as anagrams.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.