Remove duplicate characters from string

前端 未结 28 942
猫巷女王i
猫巷女王i 2020-12-01 13:09

I have to make a function in JavaScript that removes all duplicated letters in a string. So far I\'ve been able to do this: If I have the word \"anaconda\" it shows me as a

28条回答
  •  时光说笑
    2020-12-01 13:40

    function find_unique_characters(str) {
      var unique = '';
      for (var i = 0; i < str.length; i++) {
        if (str.lastIndexOf(str[i]) == str.indexOf(str[i])) {
          unique += str[i];
        }
      }
      return unique;
    }
    
    console.log(find_unique_characters('baraban'));
    console.log(find_unique_characters('anaconda'));

    If you only want to return characters that appear occur once in a string, check if their last occurrence is at the same position as their first occurrence.

    Your code was returning all characters in the string at least once, instead of only returning characters that occur no more than once. but obviously you know that already, otherwise there wouldn't be a question ;-)

提交回复
热议问题