The Wayback Machine - https://web.archive.org/web/20240528004902/https://www.geeksforgeeks.org/how-to-find-unique-characters-of-a-string-in-javascript/
Open In App

How to find unique characters of a string in JavaScript ?

Last Updated : 24 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This article aims to find unique characters in a string using JavaScript. This means that a character occurs once in the string then we cannot include it again.

Example:

Input:  Geeksforgeeks
Output: Geksforg
Input: Geeksforgeeks is a great site for computer science
Output: Geksforg Iaticmpun

We have a few methods to find unique characters in a string using JavaScript which are described below:

Approach 1: Using Naive Approach

This is a naive approach to finding unique characters from a string. In this approach, we create a variable name uniq and we iterate over the string using the for a loop at every iteration, we check if the uniq contains the character.

Example: This example shows the above-explained approach.

Javascript
function findUnique(str) {
    // The variable that contains the unique values
    let uniq = "";

    for (let i = 0; i < str.length; i++) {
        // Checking if the uniq contains the character
        if (uniq.includes(str[i]) === false) {
            // If the character not present in uniq
            // Concatenate the character with uniq
            uniq += str[i]
        }
    }
    return uniq;
}

console.log(findUnique("Geeksforgeeks"))
console.log(findUnique("Geeksforgeeks Is great"))

Output
Geksforg
Geksforg Iat

Approach 2: Using the Set

In this method, we use the set data structure. The set data structure contains only unique values, and we take advantage of it. So to extract the unique values from the string using Set we follow the steps below.

  • Using the split() method convert the string into an array.
  • Create a Set using new Set() and pass the converted array into it.
  • Now convert the set into an array using the spread operator e.g: […set]
  • And then join that array to make a string.

Example: This example shows the above-explained approach.

Javascript
// Javascript program to extract unique 
//characters from a string
function findUnique(str) {

    // Split the string to make array
    str = str.split("")

    // Create a set using array
    str = new Set(str);

    // Convert the set into array using spread 
    // operator and join it to make string
    str = [...str].join("");

    return str;
}


console.log(findUnique("Geeksforgeeks"))
console.log(findUnique("Geeksforgeeks Is a great site"))

Output
Geksforg
Geksforg Iati

Approach 3: Using the spread operator

In this approach first, we convert the string into an array using the spread operator e.g. […str] and then we apply the reduce method on that array. 

Example: This example shows the above-explained approach.

Javascript
// Javascript program to extract unique characters from a string
function findUnique(str) {
    return [...str].reduce((acc, curr) => {
        return acc.includes(curr) ? acc : acc + curr;
    }, "")
}


console.log(findUnique("Geeksforgeeks"))
console.log(findUnique("Geeksforgeeks Is great"))

Output
Geksforg
Geksforg Iat

Approach 4: Using the indexOf() Method

In this approach, we will use a for-loop in order to iterate over the complete string, and then by using the indexOf() method we will check the index of each and every character (using charAt() method) of the string which is either repeated or not repeated and then in an empty string (which we will declare initially) we will store all the unique characters.

Example: This example shows the above-explained approach.

Javascript
let uniqueCharacters = (stringg) => {
    let unique_characters = "";
    for (let i = 0; i < stringg.length; i++) {
        if (unique_characters.indexOf(stringg.charAt(i)) < 0) {
            unique_characters += stringg.charAt(i);
        }
    }
    return unique_characters;
};
console.log(uniqueCharacters("Geeksforgeeks"));

Output
Geksforg

Approach 5: Using regex

In this approach, we will use the regex expression for finding the unique element in the string.

Example: In this example, we are using regex.

Javascript
function uniqueChar(str) {
    // Use a regex pattern to match unique characters
    let uniqueChars = str.match(/(.)(?!\1)/g);

    return uniqueChars;
}
let str = "Geeksforgeeks";
let newStr = uniqueChar(str);
console.log(newStr);

Output
[
  'G', 'e', 'k', 's',
  'f', 'o', 'r', 'g',
  'e', 'k', 's'
]

Approach 6: Using _.uniq() Method

The _.uniq method is used to create an array of unique values in order, from all given arrays using SameValueZero for equality comparisons.

Example: In this example, we are using the Lodash _.uniq() method to find the unique character.

Javascript
// Requiring the lodash library
const _ = require("lodash");

// Original array
let y = "Geeksforgeeks";

// Use of _.uniq()
// method

let gfg = _.uniq(y).join('');

// Printing the output
console.log(gfg);

Output:

Geksforg

Approach 7: Using Object Property Lookup

In this approach, we use the property lookup feature of JavaScript objects. We iterate through each character of the string and set each character as a property of an empty object. Since objects cannot have duplicate keys, this effectively filters out duplicate characters. Finally, we extract the keys of the object, which gives us the unique characters, and join them to form the result string.

Example: This example demonstrates how to find unique characters in a string using object property lookup.

JavaScript
function findUnique(str) {
    let unique = {};
    for (let char of str) {
        unique[char] = true;
    }
    return Object.keys(unique).join('');
}

console.log(findUnique("Geeksforgeeks"));
console.log(findUnique("Geeksforgeeks is a great site"));

Output
Geksforg
Geksforg iat





Previous Article
Next Article

Similar Reads

JavaScript Program for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensuring all characters are the same. Given a string c
3 min read
Smallest Window in a String Containing all the Characters of Another String using JavaScript
Given two strings, "str" (the larger string) and "pattern" (the smaller string), the task is to find the smallest window in "str" that contains all the characters of "pattern" in any order using JavaScript. Examples: Input: str = "ADOBECODEBANC"pattern = "ABC"Output: BANCInput: str = "this is a test string"pattern = "tist";Output: t striTable of Co
3 min read
JavaScript Program to Find Missing Characters to Make a String Pangram
We have given an input string and we need to find all the characters that are missing from the input string. We have to print all the output in the alphabetic order using JavaScript language. Below we have added the examples for better understanding. Examples: Input : welcome to geeksforgeeks Output : abdhijnpquvxyz Input : The quick brown fox jump
3 min read
JavaScript Strip all non-numeric characters from string
In this article, we will strip all non-numeric characters from a string. In order to remove all non-numeric characters from a string, replace() function is used. Methods to Strip all Non-Numeric Characters from String:Using JavaScript replace() FunctionUsing JavaScript Regular ExpressionUsing JavaScript str.split() and array.filter() methodsMethod
2 min read
Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
JavaScript Program to Check if String Follows Order of Characters Defined by a Pattern or Not
In this JavaScript article, we will see the solution to the problem of checking if a string follows the order of characters defined by a pattern or not. We have given a string and pattern as the input and our task is to develop a program that will check whether the input string follows the same pattern according to the pattern given. Example: To so
4 min read
Add Minimum Characters at Front to Make String Palindrome in JavaScript
The minimum characters to add at the front to make the string palindrome means the smallest count of characters required to prepend to the beginning of a given string. It ensures that the resultant string reads the same forwards and backward. This process creates a palindrome from the original string with the least added characters at its start. Ap
2 min read
How to use escape characters to correctly log quotes in a string using JavaScript ?
Escape Characters are the symbols used to begin an escape command in order to execute some operation. They are characters that can be interpreted in some alternate way than what we intended to. Javascript uses '\' (backslash) in front as an escape character. Our aim is that we want to print in the console like: ""Geeks" for "Geeks" is 'the' best 'p
3 min read
Replace special characters in a string with underscore (_) in JavaScript
In this article, we will see how to replace special characters in a string with an underscore in JavaScript. These are the following method to do this: Table of Content JavaScript replace() MethodUsing Lodash _.replace() MethodJavaScript replace() MethodThis method searches a string for a defined value, or a regular expression, and returns a new st
2 min read
Add Characters to a String in JavaScript
In JavaScript, A string is a combination of multiple characters joined together to form a meaningful word. It can be a name or anything else. You can add an extra character to a string after it is defined to complete it or to practice adding characters. There are several ways available in JavaScript to achieve this task as listed below: Table of Co
4 min read