Count the Unique Words in a String using JavaScript

avatar

Borislav Hadzhiev

Last updated: Nov 14, 2021

banner

Photo from Unsplash

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.