Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting frequency of characters in a string using JavaScript

Tags:

javascript

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

For example: "aabsssd"

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

Also want to map same character as property name in object. Any good idea how to do this?

I am not sure how to do it.

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));
like image 434
Samrat Avatar asked Sep 04 '13 17:09

Samrat


People also ask

How do you count frequency in JavaScript?

const str = 'This string will be used to calculate frequency distribution'; We need to return an object that represents the frequency distribution of various elements present in the array.

How do you count the frequency of characters in a string in Java?

Example: Find Frequency of Character We loop through each character in the string using charAt() function which takes the index ( i ) and returns the character in the given index. We compare each character to the given character ch . If it's a match, we increase the value of frequency by 1.


1 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;
};
like image 199
Jonathan Crowe Avatar answered Sep 27 '22 00:09

Jonathan Crowe