【问题标题】:Counting the frequency of elements in an array in JavaScript在 JavaScript 中计算数组中元素的频率
【发布时间】:2015-02-05 09:02:48
【问题描述】:

如何计算数组中元素的频率,我是 Javascript 新手,完全迷路了,我在这里查看了其他答案,但无法让它们为我工作。非常感谢任何帮助。

function getText() {
    var userText;
    userText = document.InputForm.MyTextBox.value; //get text as string
    alphaOnly(userText);
}

function alphaOnly(userText) {
    var nuText = userText;
    //result = nuText.split("");
    var alphaCheck = /[a-zA-Z]/g; //using RegExp create variable to have only      alphabetic characters
    var alphaResult = nuText.match(alphaCheck); //get object with only alphabetic matches from  original string
    alphaResult.sort();
    var result = freqLet(alphaResult);
    document.write(countlist);
}


function freqLet(alphaResult) {
    count = 0;
    countlist = {
        alphaResult: count
    };
    for (i = 0; i < alphaResult.length; i++) {
        if (alphaResult[i] in alphaResult)
            count[i] ++;
    }
    return countlist;
}

【问题讨论】:

    标签: javascript arrays frequency


    【解决方案1】:

    要计算频率,您应该使用属性对应于输入字符串中出现的字母的对象。 此外,在增加属性值之前,您应该事先检查该属性是否存在。

    function freqLet (alphaResult) {
      var count = {};
      countlist = {alphaResult:count};
      for (i = 0; i < alphaResult.length; i++) {
        var character = alphaResult.charAt(i);
        if (count[character]) {
           count[character]++;
        } else {
           count[character] = 1;
        }
      }
      return countlist;
    }
    

    【讨论】:

    • 谢谢,但是我现在收到“TypeError: alphaResult.charAt is not a function”的错误
    • 对不起,我忘了你的 alphaResult 不是一个字符串,而是一个数组。您应该将要计算频率的字符串从您的 alphaOnly 函数传递给我的 freqLet 函数。
    【解决方案2】:

    如果您可以使用第三方库,underscore.js 提供了一个函数“countBy”,几乎可以满足您的需求。

    _.countBy(userText, function(character) {
      return character;
    });
    

    这应该返回集合中映射到计数的关联字符数组。

    然后您可以再次使用下划线或您喜欢的任何方法将该对象的键过滤为您需要的有限字符集。

    【讨论】:

      【解决方案3】:

      如下:

      var __arr = [6,7,1,2,3,3,4,5,5,5]
      
      function __freq(__arr){
          var a = [], b = [], prev 
          __arr.sort((a,b)=>{return a- b} )
      
      for(let i = 0; i<__arr.length; i++){
          if(__arr[i] !== prev){
              a.push(__arr[i])
              b.push(1)
          }else{
              b[b.length - 1]++
          }
          prev = __arr[i]
      }
      return [a , b]
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-28
        • 2013-11-27
        • 1970-01-01
        • 2019-09-12
        • 1970-01-01
        • 2020-07-10
        • 1970-01-01
        • 2017-09-14
        • 2014-03-01
        相关资源
        最近更新 更多