JavaScript Code


How to print unique characters in a string in JavaScript?


Print unique characters in a string

Given a string, get the unique characters present in the given string, and print them to console output, using JavaScript.

Solution

To get the unique characters in a string in JavaScript

  1. Convert the string to array of characters.
  2. Create a new array to store unique characters.
  3. For each character in the array of characters, if the character is not present in the unique characters, add the character to unique characters.
  4. Print unique characters to console output.

Program

1. Given a string str . Print unique characters in the string str.

var str = 'banana';

var chars = str.split("");

var uniqueChars = [];

for ( let i = 0; i < chars.length; i++ ) {
     if ( !uniqueChars.includes( chars[i] ) ) {
          uniqueChars.push( chars[i] );
     }
}

for (let i = 0; i < uniqueChars.length; i++ ) {
     console.log( uniqueChars[i] );
}