459 points
12 7 5

Remove duplicate characters in a string javascript

In this article, let us know how to remove the duplicate characters from a string. Whilst having numerous way to solve this, we focus on using the concept of Set here.

In Javascript, Set object allows to store unique values. It means only one value of same type can be stored in a set.

For example:

var set = new Set();

set.add(1); // This value isn't appended to the set

Create a Set

A set can be defined using its constructor.

Set() - creates a new set.


has(value) - checks if value if present and returns true if the value is present and false otherwise of the invoking set object.
add(value) - Appends the value to the existing values of the invoking set object. Returns the Set object with added value.
remove(value) - Removes the value specified as an argument.
clear() - Removes all the elements from the invoking Set object.

Sets and Strings

A set can be declared with string as argument to its constructor. Observe the following code snippet.

let str="kodlogs";
const myset = new Set(str);
  • string str has duplicate character "o", when we declare a set with a string as an argument it omits the duplicate characters accommodating only unique characters. Thus the output of this code snippet will be like :

Set(6) { 'k', 'o', 'd', 'l', 'g', 's' }

Solution :

Now, after comprehending the concept of Set. Let us make use of this to write a code in Javascript that eliminates the duplicate characters from a string.

var str="kodlogs";
var set=new Set(str);
var newstr='';
for(let e of set)
    newstr += e;

In the above stated example,

  • We declared a Set object of string. Thus the set now will have only the unique characters.
  • Iterating through the elements of set to phrase a new string which now doesn't contain any duplicate characters.

Hence, the output of the above code will be:


To make the code dynamic we can write a function which can be reused for multiple string values.

Hope this helps!!

More Posts

Remove duplicate characters in a string javascript DivyaN - Sep 26
Remove duplicate characters in a string javascript amna - Oct 22, 2020
How to check if a button is clicked in javascript DivyaN - Oct 18
Javascript insert character into string at position DivyaN - Oct 18
String filter javascript DivyaN - Oct 12
How to remove newline characters from the string in Javascript? Lalit Kumar - Oct 10, 2020
How to get last two characters of a string in java DivyaN - 4 days
[Javascript]Assume that x is a char variable that has been declared and already given a value. DivyaN - Oct 11
Javascript count occurrences in an array DivyaN - Oct 11
How to remove duplicate characters in a string python? Naymul01 - 3 days