0
var exampleString = 'hi, my name is Lisa Kudrov';
var stringBase = [
 'a','b','c','d','e',
 'f','g','h','i','j',
 'k','l','m','n','o',
 'p','q','r','s','t',
 'u','v','w','x','y',
 'z','_'
];
var countObject = {} ; 
function characterCount(word, character) {
 var count = 0;
 for (var i = 0; i < word.length; i++) {
   if (word[i] === character) {
       count++;
   }
 }
 return count;
 }
 for (var i = 0, l = stringBase.length; i < l; i++) {
    var currentChar = stringBase[i];
    countObject[currentChar] = characterCount(exampleString, currentChar);
 }
 console.log(countObject);

I need my output to show the letters that exist only. For example: a:1,c:1 and etc... also how can I shortcut this program in a way that when i call the function, i'll be calling characterCount('hi, my name is Lisa Kudrov')

VLAZ
  • 26,331
  • 9
  • 49
  • 67
JM Nav
  • 43
  • 6
  • 1
    Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Jan 29 '20 at 14:07
  • https://stackoverflow.com/questions/19480916/count-number-of-occurrences-for-each-char-in-a-string – Kemal AL GAZZAH Jan 29 '20 at 14:16

2 Answers2

1

You can simply group characters using Array.reduce

let characterCount = str => {
 return Object.fromEntries([...[...str.toLowerCase()].filter(c => /[a-z_]/.test(c)).reduce((acc, curr) => (acc.set(curr, acc.get(curr) +1 || 1), acc), new Map())])
}

console.log(characterCount('hi, my name is Lisa Kudrov'));
AZ_
  • 3,094
  • 1
  • 9
  • 19
  • I think only reduce can have extra braces for more readability, if required I can add. :) – AZ_ Jan 29 '20 at 14:25
0

I done this..

exampleString = 'hi, my name is Lisa_Kudrov';

function countLetters( inTxt)
{
  let counters = [...inTxt]
                      .filter(l=>/[a-z_]/.test(l))
                      .reduce((r,letter)=>
                        {
                        if(!Boolean(r[letter] )) r[letter] = 0
                        r[letter]++
                        return r
                        },{})

  console.log ('resp', counters)
}
countLetters( exampleString)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40