3

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
PM 77-1
  • 12,933
  • 21
  • 68
  • 111

4 Answers4

0

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 - 1is 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"))
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

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;
}
0

You can simply achieve this requirement with the help of Array.reduce() method.

Live Demo :

const arr = ["academy"];

const res = arr.map(word => {
  return word.split('').reduce((obj, cur) => {
    obj[cur] = obj[cur] ? obj[cur] + 1 : 1
        return obj;
  }, {});
});

console.log(res);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

I think this is the simplest:

const input = 'academy';

const res = {};

input.split('').forEach(a => res[a] = (res[a] ?? 0) + 1);

console.log(res);
vitaly-t
  • 24,279
  • 15
  • 116
  • 138