Get unique characters from a string in JavaScript
Beginner · 4 min read
Removing repeated characters from a string, keeping only the first time each one appears, is a small task with a lot of uses: cleaning up a list of tags, building the set of letters used in a word game, or checking whether a sentence uses every letter of the alphabet. The exercise gives a sentence that does exactly that: 'thequickbrownfoxjumpsoverthelazydog' should become 'thequickbrownfxjmpsvlazydg'.
In this tutorial you will write a function called unique that does it in one line using a Set. You will also write a longer version that spells out what "first occurrence" means, and see why the Set version keeps emoji in one piece. You need to know what a string and an array are.
What a Set is
A Set is a collection that holds each value only once. If you add a value it already has, nothing happens. You can build one straight from a string, because a string is a list of characters:
const letters = new Set('banana');
console.log(letters.size); // 3
console.log([...letters]); // [ 'b', 'a', 'n' ]
Two things to notice. 'banana' has six letters but only three different ones, so size is 3. And the letters come out in the order they were first seen: b, then a, then n. A Set always remembers the order things were added. That is exactly what this exercise needs.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
16 Extract the unique characters
easy"thequickbrownfoxjumpsoverthelazydog" should give "thequickbrownfxjmpsvlazydg" — first occurrences only, in order.
Stuck? Three hints, smallest first
- 1.
new Set(text)keeps insertion order and drops repeats. - 2. Spread it back into an array and
join. - 3. A Set iterates by code point, so it handles characters outside the basic range.
Step 1: Set, spread, join
Build a Set from the text, spread it back into an array with [...], and join the characters into a string:
const unique = (text) => [...new Set(text)].join('');
const pangram = 'thequickbrownfoxjumpsoverthelazydog';
console.log(unique(pangram)); // 'thequickbrownfxjmpsvlazydg'
console.log(unique('banana')); // 'ban'
That matches the expected output exactly. The o in fox is gone because there was already an o in brown; the t, h and e of the second the are gone because the first the came earlier.
Step 2: the same thing, spelled out
Before Set existed, people wrote this with indexOf. text.indexOf(c) gives the position of the first c in the text. So a character is a first occurrence exactly when its own position equals indexOf:
console.log('banana'.indexOf('a')); // 1
const uniqueByIndex = (text) => [...text].filter((c, i) => text.indexOf(c) === i).join('');
console.log(uniqueByIndex('banana')); // 'ban'
filter gives each character and its position i. For the a at position 1, indexOf('a') is 1, so it is kept. For the a at position 3, indexOf('a') is still 1, so it is dropped.
This version is slower, because indexOf searches from the start again for every character. But it states the rule plainly: keep a character only at the first place it appears.
Step 3: what counts as "the same"
Characters must match exactly. A capital and a small letter are different characters, and so is a space:
console.log(unique('BbAa')); // 'BbAa'
console.log(unique('a a b')); // 'a b'
If you want B and b treated as the same letter, lower-case the text first with unique(text.toLowerCase()).
Step 4: check for every letter
The sentence in the exercise is a pangram, a sentence that uses every letter of the alphabet. With unique, checking that is one comparison:
console.log(unique(pangram).length); // 26
console.log(pangram.length); // 35
35 characters, 26 different ones. Since the sentence has no spaces or capitals, 26 different characters means every letter from a to z is there.
Step 5: emoji stay whole
Inside JavaScript, a string is stored as small pieces called code units. Most characters take one, but many emoji take two. A Set built from a string walks through real characters, so an emoji stays in one piece:
const smile = 'a\u{1F600}a';
console.log([...unique(smile)].length); // 2
console.log(unique(smile).includes('\u{1F600}')); // true
\u{1F600} is the grinning face emoji, written as a code. The result has two characters: a and the emoji. Code that used split('') would cut the emoji into two halves before removing repeats.
The full solution
The panel has unique and uniqueByIndex. It prints the sentence, its unique characters next to the expected text, both lengths, whether it is a pangram, and the 'banana' and 'BbAa' examples. Press Run to see them.
const unique = (text) => [...new Set(text)].join('');
// Before Set existed, and it shows what "first occurrence" means.
const uniqueByIndex = (text) => [...text].filter((c, i) => text.indexOf(c) === i).join('');
const pangram = 'thequickbrownfoxjumpsoverthelazydog';
console.log('input :', pangram);
console.log('unique:', unique(pangram));
console.log('source: thequickbrownfxjmpsvlazydg');
console.log('length :', unique(pangram).length, 'from', pangram.length);
console.log('is it a pangram?', unique(pangram).length === 26);
console.log('--- order is preserved ---');
console.log("unique('banana') =", unique('banana'), '<- b, a, n in first-seen order');
console.log("unique('BbAa') =", unique('BbAa'), '<- case-sensitive');
Output
15 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 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the expected output, exactly", unique(pangram), 'thequickbrownfxjmpsvlazydg');
test('26 distinct letters, so it is a pangram', unique(pangram).length, 26);
test('first occurrences, in order', unique('banana'), 'ban');
test('a string with no repeats is unchanged', unique('abc'), 'abc');
test('an empty string stays empty', unique(''), '');
test('one character', unique('a'), 'a');
test('all the same character gives one', unique('aaaa'), 'a');
test('it is case-sensitive', unique('BbAa'), 'BbAa');
test('spaces count as characters', unique('a a b'), 'a b');
test('the index version agrees', ['banana', pangram, '', 'aaaa', 'BbAa'].every((t) => unique(t) === uniqueByIndex(t)), true);
test('every character in the result appeared in the input', [...unique(pangram)].every((c) => pangram.includes(c)), true);
test('and every input character appears in the result', [...pangram].every((c) => unique(pangram).includes(c)), true);
test('a Set iterates by code point, so there are two distinct characters', [...unique('a\u{1F600}a')].length, 2);
test('though the string is three code units long', unique('a\u{1F600}a').length, 3);
test('and the emoji survives intact', unique('a\u{1F600}a').includes('\u{1F600}'), true);
[...new Set(text)].join('') is the answer, and the reason it is the right answer is that a Set preserves insertion order. That is what makes "first occurrences, in order" fall out for free — the 'banana' assertion giving 'ban' is checking that guarantee.
The index-based version is worth seeing because it spells out the definition: keep a character only if this is the first position it appears at. It is O(n²) where the Set is O(n), but it makes the intent readable.
Iterating a string through a Set also walks code points rather than code units, so an emoji stays in one piece — the last assertions check that. split('') would have torn it in half.
Common mistakes
- Returning the
Setitself. ASetis not a string. Spread it into an array andjoin(''). - Joining with
join(). With nothing in the brackets,joinputs commas between the characters. - Expecting
uniqueto ignore case.'B'and'b'are different characters. Lower-case the text first if they should count as one.
Try it yourself
- Write
isPangram(text)that lower-cases the text, removes everything that isn't a letter, and checks for 26 unique letters. - Write
duplicates(text)that returns only the characters that appear more than once. For'banana'you should get'an'. - Use the same
Setidea to remove repeated numbers from[3, 1, 3, 2, 1].