如何在JavaScript中获得非重复字符及其计数?

时间:2015-03-15 15:48:20

标签: javascript arrays loops

这是我的代码。我应该修改这段代码以获得输出 " T-1  R-1  A-1  e-1"

(其他角色正在重复。所以不需要打印其他角色)

function different() {

    var retureArr = [];
    var count = 0;
    var complete_name = "Trammell";
    var stringLength = complete_name.length;

    for (var t = 0; t < stringLength; t++) {
        for (var s = 0; s < stringLength; s++) {
            var com1 = complete_name.charAt(t);
            var com2 = complete_name.charAt(s);

            if (com1 != com2) {
                retureArr[count] = com1;
                count++;
            }
        }

        count = 0;
    }
}

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的。您需要计算字典中每个字符的出现次数。然后您可以根据计数等于1来打印它们。

var retureArr = [];
var complete_name = "Trammell";

for (var i = 0; i < complete_name.length; i++)
{
    var key = complete_name[i];
    if (!(key in retureArr))
    {
        retureArr[key] = 1;
    }
    else
    {
        retureArr[key] = retureArr[key] + 1;
    }
}

var output = "";
for (var key in retureArr)
{
    if (retureArr[key] == 1)
    {
        output += key + "-" + retureArr[key] + " ";
    }
}

alert(output);

这会警告以下字符串:

T-1 r-1 a-1 e-1

答案 1 :(得分:0)

这很有效。但也许不是最有效的!

var string = "input string";
var stringList = [];
var outputString = "";

for (var i=0; i < string.length; i++){
    var charObject = {"Char": string.charAt(i), "Passed": false};   
    stringList.push(charObject);
}


for (var i=0; i < stringList.length; i++){
    if(!stringList[i].Passed && stringList[i].Char != " "){
        var currentCount = countOccurrences(string, stringList[i].Char);
        if(currentCount == 1){
            outputString += stringList[i].Char+"-"+currentCount + " ";
        }
        stringList[i].Passed = true;
    }
}

console.log(outputString);

function countOccurrences(string, char){
    var count = 0;
    for (var i=0; i < string.length; i++){
        if(string.charAt(i) == char){
            count++;
        }
    }
    return count;
}