I want to make a function that, given a string , counts the number of occurrences of each of its characters . With my function below I contarCaracteresV1()
could count a character of the string, but how do I do it for each one? Following a bit the response of @Orici add some things to my function contarCaracteresV2()
I see the logic but I have one undefined
of the character that was in uppercase how can I correct this? ... undefined
It was because the methods I know of for removing repeated characters leave an array with the element ''
when they remove a character; I fixed it in my answer contarCaracteresV3()
https://es.stackoverflow.com/a/293573/120346
function contarCaracteresV2(str) {
let caracteres = [... new Set(str.toLowerCase())]
for(var i=0; i<caracteres.length; i++){
let arreglo=[]
str.split('').map(n => {
if(n.toLowerCase() === caracteres[i]){
arreglo.push(n)
}
})
console.log(`La cantidad de ${caracteres[i]} es: ${arreglo.length}`);
}
}
console.log(contarCaracteresV2("Abcaa"));
function contarCaracteresV1(str) {
let letra = str[0].toLowerCase();
let arreglo=[]
str= str.split('');
str.map(n => {
if(n.toLowerCase() === letra){
arreglo.push(n)
}
})
return `La cantidad de ${letra} es: ${arreglo.length}`
}
console.log(contarCaracteresV1("Abcaa"));
I would do it the following way.
I hope it helps you.
A solution that you could apply is the following:
eg: str.replace(/\s/g, '') ===> string
)eg: [...string] ==> array
)reduce
to go through the array and pass an object as the second parameter which we will use to store the number of times each letter appears (eg: obj[char] = obj[char] + 1 || 1
)Example
Here I am returning each counted character in an object.
It can be done by accumulating the number of occurrences of each letter in an array where the index is its ascii code .
To convert a string to ascii you can use
letra.charCodeAt()
and to get the oppositeString.fromCharCode(codigo)
:This method is case sensitive.
I hope I have helped to solve the problem, greetings.