21

JavaScript を使用して、特定の文字列内の各文字の出現回数をカウントしたいと考えています。

例えば:

var str = "I want to count the number of occurances of each char in this string";

出力は次のようになります。

h = 4;
e = 4; // and so on 

Google で検索してみましたが、答えが見つかりませんでした。私はこのようなことを達成したいです; 順序は関係ありません。

4

19 に答える 19

19

これは、JavaScript (またはマップをサポートする他の言語) では非常に単純です。

// The string
var str = "I want to count the number of occurances of each char in this string";

// A map (in JavaScript, an object) for the character=>count mappings
var counts = {};

// Misc vars
var ch, index, len, count;

// Loop through the string...
for (index = 0, len = str.length; index < len; ++index) {
    // Get this character
    ch = str.charAt(index); // Not all engines support [] on strings

    // Get the count for it, if we have one; we'll get `undefined` if we
    // don't know this character yet
    count = counts[ch];

    // If we have one, store that count plus one; if not, store one
    // We can rely on `count` being falsey if we haven't seen it before,
    // because we never store falsey numbers in the `counts` object.
    counts[ch] = count ? count + 1 : 1;
}

counts各キャラクターのプロパティが追加されました。各プロパティの値はカウントです。次のように出力できます。

for (ch in counts) {
    console.log(ch + " count: " + counts[ch]);
}
于 2013-10-20T18:10:23.197 に答える
19

reduce を使用した短い答え:

let s = 'hello';
var result = [...s].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {}); 
console.log(result); // {h: 1, e: 1, l: 2, o: 1}
于 2019-04-05T17:06:19.910 に答える
2

ワンライナー ES6 の方法:

const some_string = 'abbcccdddd';
const charCountIndex = [ ...some_string ].reduce( ( a, c ) => ! a[ c ] ? { ...a, [ c ]: 1 } : { ...a, [ c ]: a[ c ] + 1 }, {} );
console.log( charCountIndex )
于 2021-04-13T12:13:44.507 に答える
2
str = "aaabbbccccdefg";

words = str.split("");

var obj = [];

var counter = 1, jump = 0;

for (let i = 0; i < words.length; i++) {
    if (words[i] === words[i + 1]) {
        counter++;
        jump++;
    }
    else {
        if (jump > 0) {
            obj[words[i]] = counter;
            jump = 0;
            counter=1
        }
        else
            obj[words[i]] = 1;
    }

}
console.log(obj);
于 2021-03-22T13:51:15.423 に答える
1

 // Converts String To Array
        var SampleString= Array.from("saleem");

        // return Distinct count as a object
        var allcount = _.countBy(SampleString, function (num) {
            return num;
        });

        // Iterating over object and printing key and value
        _.map(allcount, function(cnt,key){
            console.log(key +":"+cnt);
        });

        // Printing Object
        console.log(allcount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

    <p>Set the variable to different value and then try...</p>
    

于 2017-10-18T13:42:14.053 に答える
1

Map オブジェクトを使用しました。マップ オブジェクトでは重複キーを設定できないため、作業が簡単になります。キーが map に既に存在するかどうかを確認しています。そうでない場合は、カウントを挿入して 1 に設定しています。既に存在する場合は、値を取得してからインクリメントしています

const str = "Hello H"
    const strTrim = str.replace(/\s/g,'') // HelloH
    const strArr=strTrim.split('')

    let myMap = new Map(); // Map object 

    strArr.map(ele=>{
    let count =0
    if(!myMap.get(ele)){
    myMap.set(ele,++count)
    }else {
    let cnt=myMap.get(ele)
    myMap.set(ele,++cnt)
    }
    console.log("map",myMap)
    })
于 2020-03-04T11:53:02.883 に答える