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 で検索してみましたが、答えが見つかりませんでした。私はこのようなことを達成したいです; 順序は関係ありません。
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 で検索してみましたが、答えが見つかりませんでした。私はこのようなことを達成したいです; 順序は関係ありません。
これは、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]);
}
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}
ワンライナー 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 )
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);
// 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>
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)
})