I have a homework assignment where I have to extract duplicate characters from a string and place them in another string.
exp:
const str = "love to learn javascript"
the new string would be
const str2 = "love tarnjscip"
I didn’t made any try as I’m a beginner and I don’t have an initial idea how to start (I think the solution is a nested loop)
Can you help me and give me different ways to handle this kind of exercise?
4
Answers
here i created an empty array and i pushed to it every unique letter, then in the next round i check if a letter already added so it means the letter repeated then i call continue to skip to the next round if the letter repeated or i add the letter if it is not.
hope this works for you.
You can use an object to easily keep track of which letters you already encountered.
This code iterates through each character in the str string. It checks if the current character is a duplicate by comparing the last occurrence index with the first occurrence index of that character. If they are not equal, it means the character appears more than once.
Demo
You could use
Set
: