DEV Community

Ajay Marathe
Ajay Marathe

Posted on

2

Write a function that removes duplicate characters from a given string. ( Try to write core JS)

const removeDuplicateChar = (str1) => {
    let newArr = [];
    let stringArr = str1.split("");
    for (let i = 0; i < stringArr.length; i++) {
      if (!newArr.includes(stringArr[i])) {
        newArr.push(stringArr[i]);
      }
    }
    return newArr.join("");
  };

console.log("removeDuplicate:",removeDuplicateChar("helloooo"));
 // removeDuplicate: helo
Enter fullscreen mode Exit fullscreen mode

Problem Explanation

Imagine you have a word, and some of the letters in that word are repeated. What if you wanted to create a version of that word where each letter appears only once? That’s what the removeDuplicateCharfunction is for.

How It Works:

  • Breaking Down the Word: The function starts by splitting your word into individual letters. For example, if you have the word "helloooo", it breaks it down into ['h', 'e', 'l', 'l', 'o', 'o', 'o', 'o'].

  • Checking for Repeats: The function then goes through each letter one by one. It checks if that letter has already been added to a new list of letters. If the letter is new (meaning it hasn't been added yet), it adds it to this new list. If the letter has already been added, it skips it.

  • Building the Result: After going through all the letters, the function ends up with a list where each letter appears only once. For "helloooo", it would be ['h', 'e', 'l', 'o'].

  • Final Output: The function gives you this new list, which now contains only unique characters from the original word.
    Example:
    If you use the function with "helloooo", it will return ['h', 'e', 'l', 'o'], removing all the extra 'o's.

Image of Docusign

πŸ› οΈ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ β€’
const removeDuplicateChar = str => [...new Set([...str])]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ajaymarathe profile image
Ajay Marathe β€’

Appreciated πŸ‘

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay