How do I go through an array and say how many objects of each one exist in it?

0

The program is: you type a letter / word in the Input and click on the button (add) it appears in the div , I wanted to know how do I "scan" these words / letters and say how many of each exist .

Example: I added 10 letters A and 9 words HELLO, when I click the button (info) it should show in 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);  
}
    
asked by anonymous 09.08.2017 / 18:44

1 answer

0

If you want to catch 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 takes word letters (ie anything other than space, punctuation, line break, apostrophe, etc.). The + completes the expression so that each match is a sequence of one or more characters.

Warning: \w does not take accented characters. If you need to have accented characters, you'll need a more complex regular expression. See this question , 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 key of the object. If it is not, it creates the key with a value of one. If it is already, it increases. 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 quantity of each word, just read the keys of the object:

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

Now just integrate everything into your code. Have fun!

    
09.08.2017 / 19:52