How to count the number of times specific characters are in a string
First, and to generalize the method, it will be better if calc_fit()
takes the array of letters as an argument too. Then, you can create a Map from the array with the counter of each letter starting on 0
. Finally, you traverse the string and increment the respective counter of each letter when needed.
function calc_fit(element, fitness_let)
{
// Create a Map from the array of letters to search.
let map = new Map(fitness_let.map(l => ([l, 0])));
// Traverse the string and increment counter of letters.
for (const c of element)
{
if (map.has(c))
map.set(c, map.get(c) + 1);
}
return map;
}
let res = calc_fit("This is a string with some letters", ["e","l","m","n","t"]);
res.forEach((counter, letter) => console.log(`${letter} => ${counter}`));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
You can count occurrences with an identical value of an array using map and filter:
let str="I love JavaScript and Node.js ";
let arr=str.replace(/[^a-zA-Z]/g, '').split('');
const mapped = [...new Set(arr)].map(a => `${a} occurs ${arr.filter(a1 => a1 === a).length } time(s)`);
console.log(mapped);