I want to count the number of occurrences of each character in a given string using JavaScript.
For example:
var str = \"I want to count the number
function cauta() {
var str = document.form.stringul.value;
str = str.toLowerCase();
var tablou = [];
k = 0;
//cautarea caracterelor unice
for (var i = 0, n = 0; i < str.length; i++) {
for (var j = 0; j < tablou.length; j++) {
if (tablou[j] == str[i]) k = 1;
}
if (k != 1) {
if (str[i] != ' ')
tablou[n] = str[i]; n++;
}
k = 0;
}
//numararea aparitilor
count = 0;
for (var i = 0; i < tablou.length; i++) {
if(tablou[i]!=null){
char = tablou[i];
pos = str.indexOf(char);
while (pos > -1) {
++count;
pos = str.indexOf(char, ++pos);
}
document.getElementById("rezultat").innerHTML += tablou[i] + ":" + count + '\n';
count = 0;
}
}
}
This function will put each unique char in array, and after will find the appearances of each char in str. In my Case, i get and put data into
This is really, really simple in JavaScript (or any other language that supports maps):
// 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;
}
Now counts
has properties for each character; the value of each property is the count. You can output those like this:
for (ch in counts) {
console.log(ch + " count: " + counts[ch]);
}
I have used Map object , The map object doesn't let you set any duplicate key and that makes our job easy . I am checking if the key already exists in map , if not I am inserting and setting the count to 1 , if it already exists I am getting the value and then incrementing
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)
})
let str = "atul kumar srivastava";
let obj ={};
for(let s of str)if(!obj[s])obj[s] = 1;else obj[s] = obj[s] + 1;
console.log(obj)
Shorter answer, with 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}