8
A friend passed me the following exercise:
Create a function frequencyLetra(text) that returns an object containing the amount of occurrences of each character present in the text.
I started from the assumption that the argument passed is a string. According to my logic I created two structures of for
and the innermost has a if
to check if the letter exists in the past text. However for
more internal it does not return to the external, and terminates 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 Output:
test
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
teste2
[ 'D', 1 ]
[Finished in 0.1s]
Note that the for
the innermost wheel of the 12 interactions of the text.lenght
, but not the most external! What could I be doing wrong?
See a workaround based on count_chars() PHP created by the PHP.JS
– Bruno Augusto