JavaScript Exercises Basic#16 - Remove Duplicates from a Given String
You will be given a string. Write a program which returns a string after removing repeated characters from the string.
Result Example
Solution - Using indexOf() method
String.prototype.indexOf() The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring. Given a second argument: a number, the method returns the first occurrence of the specified substring at an index greater than or equal to the specified number.
- Iterate through the entire string.
- Get the index of each characters using indexOf method.
- If the original index of each characters(str[i]) differs from the current index(i), it means there was a duplicate.
- Add the characters to the empty answer string excluding the repeated ones.
- Return answer string.
function removeDuplicates(str) {
let answer = "";
for (let i = 0; i < str.length; i++){
if (str.indexOf(str[i]) === i) answer += str[i];
}
return answer;
}