Javascript直方图

时间:2017-12-20 15:04:49

标签: javascript histogram

我正在尝试使用javascript创建字符串中字符数的直方图。现在我有字符串来显示字符的频率,但我试图像这样显示它..

EG为字符串Hello: 答:0 B:0 C:0 d:0 E:1 F:0 ...

这是我的代码。

class myString {



  constructor(text) {
    this.text = text.toLowerCase();
    this.text = this.text.replace(/\s/g, '');
  }


  getFrequency() {

    let string = this.text
    var letters = {};
    for (var i=0; i<string.length;i++) {
        var character = string.charAt(i);
        if (letters[character]) {
           letters[character]++;
        } else {
           letters[character] = 1;
        }
    }
    return letters;
};

    Histogram(){

        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 letters = this.getFrequency();

        console.log(letters);

    }


}

我希望我的代码能像这样打印到控制台。

desired result

1 个答案:

答案 0 :(得分:1)

使用Array#map迭代stringBase,并从letters获取计数。如果字母不存在计数则使用0代替。使用Array#assignarray spread将对象数组展平为单个对象。

class myString {
  constructor(text) {
    this.text = text.toLowerCase();
    this.text = this.text.replace(/\s/g, '');
  }
  
  getFrequency() {
    const string = this.text;
    const letters = {};
    for(let i = 0; i < string.length; i++) {
      const character = string.charAt(i);
      if (letters[character]) {
        letters[character]++;
      } else {
        letters[character] = 1;
      }
    }
    return letters;
  };

  Histogram() {
    const 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'];

    const letters = this.getFrequency();

    return Object.assign({}, ...stringBase.map((l) => ({
      [l]: '*'.repeat(letters[l] || 0)
    })));
    
    /** to display in the console directly
    console.log(Object.assign({}, ...stringBase.map((l) => ({
      [l]: '*'.repeat(letters[l] || 0)
    }))));
    **/
  }
}

const str = new myString('hello');

console.log(str.Histogram());