A friend gave me the following exercise:
Create a text-frequency function that returns an object containing the number of occurrences of each character in the text.
I assumed that the argument passed is a string. According to my logic I have created two structures of for
and the inner one has a if
to check if there is the letter in the last text. However, when the inner% wrap is finished, it does not return to the outer wrapper, and ends the logic in the first iteration.
Follow the code so you can see what I'm doing:
function letterFrequence(text) {
var repeticao;
var listaComRepeticoes = [];
var text = text.split("");
for (var i = 0; i < text.length; i++) {
repeticao = 0 ;
var caractere = text[i];
console.log("test");
listaComRepeticoes.push(caractere);
for (var i = 0; i < text.length; i++) {
console.log("teste2");
if (caractere === text[i]) {
repeticao = repeticao + 1;
} else {
}
};
listaComRepeticoes.push(repeticao);
};
return listaComRepeticoes ;
}
var repeticoes = letterFrequence("David Bastos");
console.log(repeticoes);
Console Exit:
test
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
[ 'D', 1 ]
[Finished in 0.1s]
Notice that the% innermost% with% of the% of the% of the% of the innermost interacts, but the outermost does not! What could I be doing wrong?