Search code examples
javascriptarraysstringhistogramfrequency

Need help making string input return a histogram that counts frequency of letter pairs


I need to write a function(s) that takes strings as inputs and outputs a histogram of the frequency of letter pairs, in descending order.

I've managed to write a function that returns single char count, but I can't figure out how to do pairs.

Here's what I have thus far:

var string = "etc";
var histogram = {};

for (var i = 0, len = string.length; i < len; i++) {
    var char = string[i];
    if ((string[i] !== " ") && (string[i] !== " ")) {
        histogram[char] = (histogram[char] || 0) + 1;
    }
};

console.log(histogram);

The function works, and I was able to get it to leave all empty spaces out of the histogram. I'm stuck as to where to go from here, though. How to get it to evaluate pairs, and how to leave out any single char (those not followed by another char)... Any help much appreciated.


Solution

  • You need to make use of string[i+1] to get the next letter in the pair.

    And to avoid accessing outside the array when you use string[i+1], the limit of the loop should be string.length-1.

    var string = "this is a good thing";
    var histogram = {};
    
    for (var i = 0, len = string.length - 1; i < len; i++) {
      if ((string[i] !== " ") && (string[i + 1] !== " ")) {
        let pair = string.substr(i, 2);
        histogram[pair] = (histogram[pair] || 0) + 1;
      }
    };
    
    console.log(histogram);