Borislav Hadzhiev
Sun Nov 14 2021·1 min read
Photo by John Salvino
To count the unique words in a string:
Set()
constructorsize
property on the Set
object.size
property returns the number of elements contained in the Set
.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.
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.
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.