Emmanuel Akinfulubi

JavaScriptString

Find the most common character in a string in JavaScript

Intermediate ยท 4 min read

Counting how often each thing appears is one of the most useful small programs you can write. Count the letters in a word and you can find the most common one, spot duplicates or check whether two words are anagrams. The same idea counts votes, tags or page visits.

In this tutorial you will count the letters in 'banana', find the commonest, and then see two surprises that make a Map a better container than a plain object for this job. You should know what a loop, an object and an array are. Map is explained below.

The counting pattern

The idea is always the same:

  1. Start with an empty container.
  2. Walk through the items one at a time.
  3. For each item, add one to its count. If it has no count yet, start it at one.

Objects and Maps

A plain object, {}, stores values under keys: counts['a'] = 3. A Map does the same job with methods instead of brackets: counts.set('a', 3) stores a value and counts.get('a') reads it. A Map is built for this kind of job, while a plain object also has to act as a general-purpose record. You will see in Steps 5 and 6 why that difference matters.

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

34 Count how often each character appears

fair

Count the letters in 'banana' and report the commonest. Then count '2211' and look at the order of the keys.

Stuck? Three hints, smallest first
  1. 1. Walk the string with for...of and accumulate into an object or a Map.
  2. 2. for...of iterates code points, so an emoji is counted once.
  3. 3. Object keys that look like array indexes are reordered; a Map never reorders.

Step 1: count with an object

Step 1

function countCharacters(text) {
  const counts = {};
  for (const c of text) counts[c] = (counts[c] || 0) + 1;
  return counts;
}
console.log(countCharacters('banana')); // { b: 1, a: 3, n: 2 }

for (const c of text) gives one character at a time. The first time we see a, counts['a'] is undefined, so counts[c] || 0 gives 0 and the count becomes 1. After that it is a number, so it goes up by one each time.

Step 2: check the edges

Step 2

function countCharacters(text) {
  const counts = {};
  for (const c of text) counts[c] = (counts[c] || 0) + 1;
  return counts;
}
console.log(countCharacters(''));      // {}
console.log(countCharacters('a a')); // { a: 2, ' ': 1 }
console.log(countCharacters('Aa'));  // { A: 1, a: 1 }
console.log(countCharacters('a๐Ÿ‘๐Ÿ‘')); // { a: 1, '๐Ÿ‘': 2 }

An empty string gives an empty object. A space is a character, so it is counted. Capital and small letters are different characters. And because for...of walks the string one whole character at a time, each emoji is counted once rather than as two halves.

Step 3: find the most common

Object.entries turns an object into an array of [key, value] pairs. Sort those pairs by count, biggest first, and take the first:

Step 3

function countCharacters(text) {
  const counts = {};
  for (const c of text) counts[c] = (counts[c] || 0) + 1;
  return counts;
}
const mostCommon = (text) =>
  Object.entries(countCharacters(text)).sort((a, b) => b[1] - a[1])[0];
console.log(mostCommon('banana')); // [ 'a', 3 ]

a and b in the sort function are two pairs. b[1] - a[1] compares their counts. A positive result puts b first, so the largest count ends up at the front.

Step 4: the totals add up

Step 4

function countCharacters(text) {
  const counts = {};
  for (const c of text) counts[c] = (counts[c] || 0) + 1;
  return counts;
}
const total = Object.values(countCharacters('banana')).reduce((a, b) => a + b, 0);
console.log(total); // 6

Object.values gives just the counts, [1, 3, 2], and reduce adds them. Six letters in, six counted. It is a quick check that nothing was missed.

Step 5: digits get reordered

Now count '2211'. The 2s came first, so you might expect the key '2' to come first:

Step 5

function countCharacters(text) {
  const counts = {};
  for (const c of text) counts[c] = (counts[c] || 0) + 1;
  return counts;
}
console.log(Object.keys(countCharacters('2211'))); // [ '1', '2' ]

A plain object puts keys that look like whole numbers (array positions) first, in number order. So the order you saw them in is lost.

Step 6: an object already has keys

Step 6

function countCharacters(text) {
  const counts = {};
  for (const c of text) counts[c] = (counts[c] || 0) + 1;
  return counts;
}
console.log(typeof countCharacters('x').constructor); // 'function'

We never counted a character called constructor, yet the object has it. Every plain object inherits a few built-in properties. If you count words instead of letters and someone types the word "constructor", counts['constructor'] || 0 finds a function instead of a count, and the result is nonsense.

Step 7: count with a Map

Step 7

function countByMap(text) {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  return counts;
}
console.log([...countByMap('2211').keys()]);   // [ '2', '1' ]
console.log(countByMap('x').get('constructor')); // undefined

?? gives the right side only when the left is null or undefined, so a missing count starts at 0. A Map keeps keys in the order they were added, and it starts truly empty. Both surprises are gone.

The full solution

Here is the complete answer: the object version, mostCommon, the Map version and checks for the key order and the inherited constructor. Press Run and compare the two key lists printed for '2211'.

The answer

function countCharacters(text) {
  const counts = {};
  for (const c of text) counts[c] = (counts[c] || 0) + 1;
  return counts;
}

function countByMap(text) {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  return counts;
}

const mostCommon = (text) =>
  Object.entries(countCharacters(text)).sort((a, b) => b[1] - a[1])[0];

console.log('banana :', countCharacters('banana'));
console.log('commonest:', mostCommon('banana'));
console.log("countCharacters('2211') keys :", Object.keys(countCharacters('2211')), '<- reordered');
console.log("countByMap('2211') keys      :", [...countByMap('2211').keys()], '<- as they arrived');

Output


      
11 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 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('the letters of banana', countCharacters('banana'), { b: 1, a: 3, n: 2 });
test('an empty string has no counts', countCharacters(''), {});
test('spaces are characters too', countCharacters('a a')[' '], 1);
test('case is not folded', countCharacters('Aa'), { A: 1, a: 1 });
test('the commonest letter, with its count', mostCommon('banana'), ['a', 3]);
test('for...of walks code points, so an emoji counts once', countCharacters('a๐Ÿ‘๐Ÿ‘')['๐Ÿ‘'], 2);
test('the totals add up to the number of code points', Object.values(countCharacters('banana')).reduce((a, b) => a + b, 0), 6);
test('digit keys are pulled to the front, because they look like indexes', Object.keys(countCharacters('2211')), ['1', '2']);
test('a Map keeps the order they arrived in', [...countByMap('2211').keys()], ['2', '1']);
test('a plain object already has an inherited constructor property', typeof countCharacters('x').constructor, 'function');
test('which a Map is immune to', countByMap('x').get('constructor'), undefined);

Two reasons to prefer a Map here, and both are asserted. Integer-like keys are re-sorted to the front of a plain object, so counting digits gives you the keys in numeric order rather than in the order they appeared. And a plain object arrives with inherited names already on it, so counts['constructor'] is a function before you have counted anything.

Object.create(null) fixes the second problem and not the first. A Map fixes both, and it also keeps 1 and '1' as distinct keys, which an object cannot.

Common mistakes

  • Forgetting the starting value. counts[c] + 1 on a new key is undefined + 1, which is NaN. Use (counts[c] || 0) + 1.
  • Relying on object key order. Number-like keys are moved to the front. Use a Map when order matters.
  • Using split('') to walk the text. It cuts emoji in half. Use for...of.

Try it yourself

  1. Change countCharacters so 'A' and 'a' are counted together.
  2. Skip spaces, so 'a a' gives a count only for a.
  3. Return every character tied for the top count, so 'aabb' gives ['a', 'b'].

Keep practising

Newsletter

New writing, when it lands.

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