i have an array ["academy"]
and i need count chars from the string in the array.
output:
a:2
c:1
d:1
e:1
m:1
y:1
like this
i tried two for loops
function sumChar(arr){
let alph="abcdefghijklmnopqrstuvxyz";
let count=0;
for (const iterator of arr) {
for(let i=0; i<alph.length; i ){
if(iterator.charAt(i)==alph[i]){
count ;
console.log(`${iterator[i]} : ${count}`);
count=0;
}
}
}
}
console.log(sumChar(["abdulloh"]));
it works wrong
Output:
a : 1
b : 1
h : 1
undefined
CodePudding user response:
To count the number of occurrences of each character in a string, you can use a for loop to iterate through the string and add each character to an object as a key, with the value being the number of times it occurs. Here is an example:
// create an empty object to store the character counts
var charCounts = {};
// get the string from the array
var str = ["academy"][0];
// iterate through the string and count the occurrences of each character
for (var i = 0; i < str.length; i ) {
var char = str[i];
if (charCounts[char] === undefined) {
// if the character has not been encountered before, set its count to 1
charCounts[char] = 1;
} else {
// if the character has been encountered before, increment its count by 1
charCounts[char] ;
}
}
// print the character counts
for (var char in charCounts) {
console.log(char ": " charCounts[char]);
}
CodePudding user response:
Here's a concise method. [...new Set(word.split(''))]
creates an array of letters omitting any duplicates. .map
takes each letter from that array and runs it through the length checker. ({ [m]: word.split(m).length - 1 })
sets the letter as the object key
and the word.split(m).length - 1
is a quick way to determine how many times that letter shows up.
const countLetters = word => (
[...new Set(word.split(''))].map(m => ({
[m]: word.split(m).length - 1
})))
console.log(countLetters("academy"))
CodePudding user response:
You can check the occurrences using regex also. in this i made a method which checks for the character in the string. Hope it helps.
word: string = 'abcdefghijklkmnopqrstuvwxyzgg';
charsArrayWithCount = {};
CheckWordCount(): void {
for(var i = 0;i < this.word.length; i ){
if(this.charsArrayWithCount[this.word[i]] === undefined){
this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);
}
}
console.log(this.charsArrayWithCount);
}
charCount(string, char) {
let expression = new RegExp(char, "g");
return string.match(expression).length;
}