Find unique Characters in a String

Find unique Characters in a String

ยท

2 min read

Hey ๐Ÿ‘‹๐Ÿป,

Today I'll be discussing how we can find out the unique characters in a string using different approaches and languages. Let's start ๐Ÿ

Using Set

There are a few ways we can use to find the unique characters in a string. The simplest way is by using the Set. The Set object lets you store unique values of any type, whether primitive values or object references.

Let's name the function returning a unique string - removeDupes, that accepts the original string as input.

function removeDupes(str) {
  // Split the string into array of characters using the split() method.
  let arr = str.split()

  // Create a new set from the array of characters
  let demoSet = new Set(arr)

  // The formation of set will remove all the duplicate items. Now we can use the Array
  // for storing the values.
  let arrayNew = Array.from(demoSet)

  // Empty string to store final answer
  var uniqueStr = ""

  // Use the forEach loop to iterate over the array
  arrayNew.forEach(element => {
    uniqueStr += element
  })

  return uniqueStr
}

Using Objects / Hashmaps

Another available option to find the unique elements in a string can be using the objects/hashmaps. We can simply store the character and the number of its occurrences. Later we can print the number of times that character occurs once.

This approach is quite useful when there are certain conditions mentioned for example to only print the last occurrence of the character etc.

// Empty Object to store chars and their count
// e.g: { a : 2, b : 1 }
let listOfChars = {};

function removeDupes(str) {
  // Split the array
  let arr = str.split("");

  // Populate the values in the Object
  for (var i = 0; i < arr.length; i++) {
    if (isNaN(listOfChars[arr[i]])) {
      listOfChars[arr[i]] = 1;
    } else {
      listOfChars[arr[i]] += 1;
    }
  }

  // Unique String / Final Answer
  var uniqueStr = "";

  // Using the forin loop to iterate over Object
  for (key in listOfChars) {
    if (listOfChars[key] >= 1) {
      uniqueStr += key;
      listOfChars[key] = 0;
    }
  }

  return uniqueStr;
}

Using the filter method

In the filter method we can check the position of a character and then filter them out at their first index using the indexOf method.

function removeDupes(str) {
  return str.split('')
    .filter(function(item, pos, self) { 
        // Find the index of a character and filter it out.
        return self.indexOf(item) == pos; 
      })
    .join('');
}

I hope this blog post was useful for you. Follow me for more such content.

ย