[英]How to check for multiple occurrences of word in string or array
I need to get the count of a specified set duplicate words in a string. 我需要获取字符串中指定集合重复单词的计数。
I can return the occurrences of one word but I am stuck at multiple words. 我可以返回一个单词的出现,但我卡在多个单词中。
const sData = 'am=1&am=2&pm=1&pm=2&pm=3&ac=1&dc=1';
const aData = sData.split('&');
const nData = aData.filter(el => el.includes('am')).length;
This returns 2
which is expected but I need to do the same for pm
, ac
and dc
and as I understand includes
does not accept multiple values. 这将返回
2
,这是预期的,但我需要对pm
, ac
和dc
进行相同的操作,并且据我所知, includes
不接受多个值。
You can encompass repeated work using functions ! 您可以使用功能进行重复工作!
const countOccurrencesOf = (word, search) => {
return word.filter(el => el.includes(search)).length;
};
Now, you can re-use this function for all of your other string finding needs: 现在,您可以重新使用此函数来满足其他所有查找字符串的需求:
countOccurrencesOf(aData, 'pm');
countOccurrencesOf(aData, 'ac');
countOccurrencesOf(aData, 'dc');
What you're looking for, is a recursive function. 您正在寻找的是递归函数。 Within the example you have provided, I'm assuming your parsing URL Query variables.
在您提供的示例中,我假设您正在解析URL查询变量。 So, let's pretend that the following are your delimiters: & or =.
因此,让我们假设以下是您的分隔符:&或=。
This function shows a general idea of what it seems like you're trying to acheive. 此功能显示了您想要达到的效果的总体思路。
function containsDuplicates(string,delimiter,foundDuplicates){
var str = string.split(delimiter);
if(foundDuplicates.includes(str)){
return true;
}else if(string.indexOf(str) < string.length){
foundDuplicates.push(str);
return containsDuplicates(string,delimiter,foundDuplicates);
}
else{
return false;
}
}
Try using map instead: 尝试使用地图代替:
const sData = 'am=1&am=2&pm=1&pm=2&pm=3&ac=1&dc=1';
const aData = sData.split('&');
// define the stings you want to count
const nData = {am: 0, pm: 0, ac: 0}
// iterate over the split input data
const val = aData.map((obj) => {
// iterate over the nData
Object.keys(nData).forEach((count) => {
// if the input contains the count, add to the count
if (obj.includes(count)) nData[count]++;
})
})
console.log(nData); // returns: { am: 2, pm: 3, ac: 1 }
Reduce would probably work as well! 减少可能也会起作用!
|
|
分隔单词来创建正则表达式 . match
get all the matches for the keywords specified. match
获取指定关键字的所有匹配项。 counter
object. counter
对象。 Loop through the array of matches and count each occurrence const str = 'am=1&am=2&pm=1&pm=2&pm=3&ac=1&dc=1', toFind = ['am', 'pm', 'ac'], regex = new RegExp(toFind.join("|"), "g"), matches = str.match(regex); console.log(matches) const counter = {}; matches.forEach(m => counter[m] = counter[m] + 1 || 1) console.log(counter)
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.