Remove duplicate characters from string

前端 未结 28 863
猫巷女王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:42

    Yet another way to remove all letters that appear more than once:

    function find_unique_characters( string ) {
        var mapping = {};
        for(var i = 0; i < string.length; i++) {
            var letter = string[i].toString();
            mapping[letter] = mapping[letter] + 1 || 1;
        }
        var unique = '';
        for (var letter in mapping) {
            if (mapping[letter] === 1)
                unique += letter;
        }
    
        return unique;
    }
    

    Live test case.

    Explanation: you loop once over all the characters in the string, mapping each character to the amount of times it occurred in the string. Then you iterate over the items (letters that appeared in the string) and pick only those which appeared only once.

提交回复
热议问题