Count the Unique Words in a String using JavaScript

avatar

Borislav Hadzhiev

Sun Nov 14 20211 min read

banner

Photo by John Salvino

Count the Unique Words in a String #

To count the unique words in a string:

  1. Split the string on a space.
  2. Pass the result to the Set() constructor
  3. Access the size property on the Set object.
  4. The size property returns the number of elements contained in the Set.
index.js
const str = 'hello one two three hello'; const count = new Set(str.split(' ')).size; console.log(count); // ๐Ÿ‘‰๏ธ 4

We used the String.split method to split the string on a space.

The method returns an array containing the substrings.

index.js
const str = 'hello one two three hello'; // ๐Ÿ‘‡๏ธ ['hello', 'one', 'two', 'three', 'hello'] console.log(str.split(' '));

To remove the duplicates from the array, we pass the array of words to the Set() constructor.

The Set() constructor takes an iterable as an argument and converts it to a Set object.

Set objects only store unique values, so any of the duplicates are excluded.

To get the count of unique words, we access the size property on the Set.

The size property returns the number of elements in the Set. In our case, this is the number of unique words the string contains.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee