Counting the frequency of characters in a string using javascript

I need to write some kind of loop that can count the frequency of each letter in a string.

For example: "aabsssd"

: a: 2, b: 1, s: 3, d: 1

You also need to match the same character as the name of the property in the object. Any good idea how to do this?

I am not sure how to do this.

This is where I am so far:

var arr = ["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"]; function counter(x) { var count=0, temp = []; x = x.split(''); console.log(x); for(var i=0, len = x.length; i < len; i++) { if(x[i] == "a") { count++; } } return count; } var a = "aabbddd"; console.log(counter(a)); 
+12
javascript
source share
17 answers

Here you go:

 function getFrequency(string) { var freq = {}; for (var i=0; i<string.length;i++) { var character = string.charAt(i); if (freq[character]) { freq[character]++; } else { freq[character] = 1; } } return freq; }; 
+20
source share

some ES6 syntax with reduction:

 let counter = str => { return str.split('').reduce((total, letter) => { total[letter] ? total[letter]++ : total[letter] = 1; return total; }, {}); }; counter("aabsssd"); // => { a: 2, b: 1, s: 3, d: 1 } 
+11
source share

Another solution:

 function count (string) { var count = {}; string.split('').forEach(function(s) { count[s] ? count[s]++ : count[s] = 1; }); return count; } 
+7
source share

A more declarative way to get a histogram of words would be to use abbreviation to repeat letters and create a new object that contains letters as keys and frequencies as values.

 function getFrequency(str) { return str.split('').reduce( (prev, curr) => { prev[curr] = prev[curr] ? prev[curr] + 1 : 1; return prev; }, {}); }; console.log(getFrequency('test')); // => {t: 2, e: 1, s: 1} 
+2
source share

Here is another option using underscore.js:

 function charCount(str) { return _(str.split('')).countBy(function(char) { return char.toLowerCase(); }); } 

charCount('aaabbbbdd') outputs Object {a: 3, b: 4, d: 2}

0
source share
 for(i = strlen(string)var string = 'aabsssd'; var chars = new Array(); for(var i = 0; i < string.length; i++){ var char = string.charAt(i); if(chars[char] == undefined){ chars[char] = 0; } chars[char]++; } console.log(chars); 
0
source share

  const recorrences = ['a', 'b', 'c', 'a', 'b','a'] .map(i => !!~i.indexOf('a')) .filter(i => i) .length; console.log(`recorrences ${recorrences}`) //recorrences 3 
0
source share

Here is another way:

 const freqMap = s => [...s].reduce((freq,c) => {freq[c] = -~freq[c]; return freq} ,{}) 

Or, if you prefer the "for" loop:

 function freqMap(s) { freq={}; for (let c of s) freq[c]=-~freq[c]; return freq; } 

for example, freqMap ("MaMaMia") returns an object {M: 3, a: 3, i: 1}

This method uses the fact that in javascript, bitwise not at "undefined" it gives -1, while "undefined + 1" gives NaN). So, - ~ undefined is 1, - ~ 1 is 2, - ~ 2 is 3, etc.

Thus, we can iterate over the characters of a string and simply increment freq [c] without any "if". The first time we encounter the character c, freq [c] will be undefined, so we set it to - ~ freq [c], which is 1. If we subsequently meet c again, we will set freq [c] to again - ~ freq [c], which will now be 2, etc.

Simple, elegant, concise.

0
source share

simpler and more functional solution:

using arrows ES6 & Logical operators:

 const buildFreqDict = string => string.split('').reduce((freqDict, char) => { freqDict[char] = (freqDict[char] || 0) + 1; return freqDict; }, {}) console.log(buildFreqDict("banana")) 

Explanation

  • split a string into an array of characters.
    • and then pass it to the Reduce method (using method.chaining ()).
  • if char is already in countDict, then add 1 to it.
    • or if the character is not found in countDict, set it to 1.
  • return new values ​​back to reduce the storage object
  • NB: do not forget to include the third argument .reduce () : in this case it is {} (object literal), which serves to initialize the freqDict object.

for more information, see Counting value instances in an object halfway down the page: MDN Reduce
and for more information on using logical operators, see here: MDN Logical Operators.

0
source share
 // Count frequency of characters in a string // input: 'Hello, I'm Paul!' // result: { // H: 1, // E: 1, // L: 3, // ... and so on ... // } const countChars = (string) => { let charStats = {}; string = string.replace(' ', '').toUpperCase().split(''); string.forEach((char) => { if (charStats[char]) { charStats[char]++; } else { charStats[char] = 1; } }); return charStats; }; 
0
source share

Another solution

  function maxChar(str) { const charMap = {}; let max = 0; let maxChar = ''; for(let char of str){ if(charMap[char]){ charMap[char]++; }else{ charMap[char] = 1; } } for(let char in charMap){ if(charMap[char] > max){ max = charMap[char]; maxChar = char; } } return maxChar; } 

===>

  maxChar('355385') "5" 
0
source share
 var str = 'abcccdddd'; function maxCharCount(target) { const chars = {}; let maxChar = ''; let maxValue = 1; for (let char of target) { chars[char] = chars[char] + 1 || 1; } return chars; } console.log(maxCharCount(str)); 
0
source share

The same solution, but refactoring. It's great that we can solve this problem with a lot of different answers :)

 function getFrequency(string) { var freq = {}; for (let character in string) { let char = string[character]; (freq[char]) ? freq[char]++ : freq[char] = 1 } return freq; }; 
0
source share

You can use this. Just pass the string and it will return the object with all the frequency of characters.

 function buildCharMap(string) { const charMap = {}; string.replace(/[^\w]/g, '').toLowerCase(); for (let char of string) { charMap[char] = charMap[char] + 1 || 1; } return charMap; } 
0
source share

Cheat code for counting the frequency of a character in a string

 let target = "e"; let string = " i want to see that person that came in here last"; let frequency = string.split(target).length; 

or all in one line

 console.log(string.split("e").length) 
0
source share

The Easy Way In addition, you will get an alphabetically sorted list. It passes through the array and evaluates whether the symbol is already in the object: if false, the symbol is added to the object, if true, its frequency increases by one.

 const text= "Lorem ipsum dolor sit amet consectetur adipiscing" const textAsArray = text.split('').sort() let charactersList = {} for (char of textAsArray) { if (!charactersList[char]) { charactersList[char]=1; } else { charactersList[char]++ } } console.log(charactersList) 
0
source share

I have reviewed and think that it adapts very well to the needs that they represent. I would like it to be on the same line, but I don’t know how to generate the object dynamically.

 const uniqueCount=(arr)=>{ let rs ={}; arr.sort().join("").match(/(.)(\1*)/g).map(i=>rs[i[0]]=i.length); return rs; }; console.log(uniqueCount(["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"])); //{ a: 3, b: 2, c: 2, d: 2, e: 2, f: 1, g: 1, h: 3 } 

I find it very successful to use .match() and regular expressions /(.)(\1*)/g as described above.

If it's just a string, you just need to add .split("") before that and that’s it.

0
source share

All Articles