How to find frequency of characters in a string in JavaScript?
The frequency is the number of time a character appear in the string. Solving programming problems related to strings often require finding frequency.
The following are a few approaches to find frequency of characters in a string in JavaScript:
Approach #1
function getFrequency(string) { const freq = {}; for (let i = 0; i < string.length;i++) { const character = string.charAt(i); freq[character] ? freq[character]++ : freq[character] = 1; } return freq; } getFrequency('aabsssd'); // {a: 2, b: 1, s: 3, d: 1}
Approach #2
const counter = str => { return str.split('').reduce((arr, letter) => { arr[letter] ? arr[letter]++ : arr[letter] = 1; return arr; }, {}); }; console.log(counter("aabsssd")); // {a: 2, b: 1, s: 3, d: 1}
Approach #3
function getFrequency(string) { const freq = new Map(); for (let i = 0; i < string.length; i++) { const character = string.charAt(i); freq.set(character, freq.get(character) + 1 || 1); } return freq; } getFrequency('aabsssd'); // {a: 2, b: 1, s: 3, d: 1}