Showing unique characters in a string only once

后端 未结 13 2329
-上瘾入骨i
-上瘾入骨i 2020-12-31 20:38

I have a string with repeated letters. I want letters that are repeated more than once to show only once. For instance I have a string aaabbbccc i want the result to be abc.

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 20:54

    Per the actual question: "if the letter doesn't repeat its not shown"

    function unique_char(str)
    {
        var obj = new Object();
    
        for (var i = 0; i < str.length; i++)
        {
            var chr = str[i];
            if (chr in obj)
            {
                obj[chr] += 1;
            }
            else
            {
                obj[chr] = 1;
            }
        }
    
        var multiples = [];
        for (key in obj)
        {
            // Remove this test if you just want unique chars
            // But still keep the multiples.push(key)
            if (obj[key] > 1)
            {
                multiples.push(key);
            }
        }
    
        return multiples.join("");
    }
    
    var str = "aaabbbccc";
    document.write(unique_char(str));
    

提交回复
热议问题