I am trying to create a function that looks to see if any of the characters in an array are in a string, and if so, how many.
I have tried to calculate every pattern, but there is too much. I tried using the alternative to the "in" operator from Python, but that didn't work out as well
function calc_fit(element) {
var fitness_let = ["e", "l", "m", "n", "t"]
}
}
The element
is the string, and the fitness_let array is the array of things that I need to check to see if they are in the string, and if so, how many.
First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
Count Number of Occurrences in a String with . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.
Python String count() Method The count() method searches (case-sensitive) the specified substring in the given string and returns an integer indicating occurrences of the substring. By default, the counting begins from 0 index till the end of the string.
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);
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;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With