Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the frequency of elements in an array in JavaScript

how do I count the frequency of the elements in the array, I'm new to Javascript and completely lost, I have looked at other answers here but can't get them to work for me. Any help is much appreciated.

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;
}
like image 809
Confuddled Avatar asked Dec 06 '25 17:12

Confuddled


1 Answers

To count frequencies you should use an object which properties correspond to the letters occurring in your input string. Also before incrementing the value of the property you should previously check whether this property exists or not.

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;
}
like image 59
zavg Avatar answered Dec 08 '25 06:12

zavg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!