How to go through an array and tell how many objects of each exist in it?

Asked

Viewed 1,178 times

0

The program is: you type a letter/word in the Input and click on button(add) it appears in div, i was wondering how do I "scan" these words/letters and tell how many of each there are.

Example: I added 10 A letters and 9 HELLO words, when I click the button(info) it should show on alert the amount.

Code:

function adc () {
  var text = document.getElementById("textoadc").value;
      var node = document.createElement("OL");
      node.className="ITEM";

  var test = document.createTextNode(text);
  
      document.body.appendChild(node).appendChild(test);  
}

  • You want to count how many times a word appears within a given element, that’s it?

1 answer

0

If you want to pick up the words, you can use a regular expression. So:

let texto;
// preencha a variável acima da forma que achar melhor
let palavras = texto.match(/\w+/g);

Explanation: the regular expression \w take letters of words (i.e.: anything that is not space, punctuation, line break, apostrophe, etc.). The + complements the expression so that each match is a sequence of one or more characters.

Heed: \w does not take accented characters. If you need to count accented characters, you will need a more complex regular expression. See this question about this, from which we can deduce two regular expressions:

/[a-záàâãéèêíïóôõöúçñ']+/gi

Or:

/[a-zA-Z\u00C0-\u00FF']+/gi

Next comes the coolest part. Every Javascript object is a hashmap. Then you create an empty object, and for each word you check if it is already the key of the object. If it is not, create the key with value one. If it is already, increase. So:

let mapa = {};
for (let i = 0; i < palavras.length; i++) {
    let chave = palavras[i];
    if (!mapa[chave]) {
        mapa[chave] = 1;
    } else {
        mapa[chave]++;
    }
}

At the end of this, to check the amount of each word, just read the object keys:

for (let chave in mapa) {
    console.log(mapa[chave]); // exemplo ilustrativo
}

Now just integrate everything into your code. Have fun!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.