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
- Convert the string to array of characters.
- Create a new array to store unique characters.
- For each character in the array of characters, if the character is not present in the unique characters, add the character to unique characters.
- 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] );
}