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

Screenshot 2022-04-28 at 17.21.17.png


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.

  1. Iterate through the entire string.
  2. Get the index of each characters using indexOf method.
  3. If the original index of each characters(str[i]) differs from the current index(i), it means there was a duplicate.
  4. Add the characters to the empty answer string excluding the repeated ones.
  5. 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;
        }