我正在尝试创建一个函数,以查看数组中的任何字符是否在字符串中,如果是,则多少个字符。
我尝试计算每种模式,但是太多了。我尝试使用Python中“ in”运算符的替代方法,但效果不佳
function calc_fit(element) {
var fitness_let = ["e", "l", "m", "n", "t"]
}
}
element
是字符串,而Fitness_let数组是我需要检查的东西数组,以查看它们是否在字符串中,如果是,则检查多少。
答案 0 :(得分:11)
您可以使用 map 和 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);
答案 1 :(得分:3)
首先,为了概括该方法,最好将calc_fit()
也采用字母数组作为参数。然后,您可以从数组创建一个Map,每个字母的计数器从0
开始。最后,遍历字符串并在需要时增加每个字母的相应计数器。
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;}
答案 2 :(得分:0)
一种方法是迭代数组,并对每个字母进行全局正则表达式删除。然后,将替换后的字符串长度与原始输入长度进行比较,以确定出现的次数。
function calc_fit(element) {
var fitness_let = ["e", "l", "m", "n", "t"];
for (var i=0; i < fitness_let.length; i++) {
var letter = fitness_let[i];
var numtimes = element.length - element.replace(new RegExp(letter, 'g'), '').length;
console.log(fitness_let[i] + " occurs: " + numtimes + " times.");
}
}
var input = "elements are elemental";
calc_fit(input);
答案 3 :(得分:0)
如果您想获得否。每个角色出现的次数比您可以使用reduce
和Map
let getTotal = (element) => {
let fitness = ["e", "l", "m", "n", "t"]
let newMap = new Map(fitness.map(v=>[v,v]))
return element.split('').reduce((op,inp)=>{
if(newMap.has(inp)){
op[inp] = op[inp] || 0
op[inp]++
}
return op
},{})
}
console.log(getTotal('element'))
console.log(getTotal('eleabc'))
您可以使用join来构建带有交替|
和单词边界的正则表达式,以获取总数
let getTotal = (element) =>{
let fitness = ["e", "l", "m", "n", "t"]
let reg = '\\b' + fitness.join('|') + '\\b'
let pattern = new RegExp(reg,'gi')
return (element.match(pattern) || []).length
}
console.log(getTotal('element'))
console.log(getTotal('eleabc'))
答案 4 :(得分:0)
您可以创建一个哈希映射并利用reduce来计数找到的所有实例
示例:
const counts = {};
["e", "l", "m", "n", "t"].forEach( e => counts[e] = 0 );
const letters = "hey look! a string!".split("");
const results = letters.reduce( (acc, curr) => {
if (acc.hasOwnProperty(curr)) { acc[curr] += 1; }
return acc;
}, counts);
console.log(results);
答案 5 :(得分:0)
这里有一个稍微不同的方法,它依赖于函数生成器。
在其他解决方案上使用此功能没有相关的原因,但是它可以在整个周期内提供额外的控制。
请注意,字符串仅迭代一次,因此整个“迭代”周期应该非常快。
说明直接在下面的代码中。
输出是一个对象,其中每个键都是一个字符,并保留出现的次数,并保留所有搜索到的指针。
如果未传递搜索的字符数组,它将自动在calc_fit函数内部构建,这将分别返回大写和小写的出现,包括标点和符号。不过,这很容易自定义。
// Iterates a string and yield the current looped char if it exists in the chars list.
function* matchChars(s, chars) {
for (var char of s) {
if (chars.indexOf(char) > -1) yield { char: char };
}
}
// not sure why the function was named in this way in the original code, but hey, it's the OP's function name.
function calc_fit(element, chars) {
chars = chars || [...new Set(element)];
// builds an object from the above array, where the structure has the key which is the char, and the value which is initially 0.
const matchList = chars.reduce((acc,next) => (acc[next] = 0, acc), {});
// Iterates all the matches. For each match, it increments the amount of matches of matchList.
for (var match of matchChars(element, chars)) matchList[match.char]++;
// finally, returns matchList.
return matchList;
}
// assertions: should match all the characters.
console.log(calc_fit('element', ["e", "l", "m", "n", "t"]));
// assertions: should return all zeros.
console.log(calc_fit('', ["e", "l", "m", "n", "t"]));
// assertions: should automatically detect chars, even upper case and lower case.
console.log(calc_fit('hello, world. ThIs is beatiful!'));