简体   繁体   中英

How can I count the occurrences of a word in an array of strings using javascript?

If I have this array

const arr1 = ["cat", "I love cats and I have many cats", "dog"]

and running arr1.filter(s => s.includes("cat")).length; results to 2, because "cat" is included in 2 entries but is there a way that the result be equal to 3? Meaning that instead of entries, occurrences of the word will be counted.

Split the strings by the search value. The results will be an array containing one more than the number of instances. Iterate over each string in the array in this way and sum the counts accordingly.

 const countInstances = (value, arr) => arr.reduce( (a,v) => a += v.split(value).length-1, 0); console.log(countInstances('cat', ["cat", "I love cats and I have many cats", "dog"]));

The non-obvious bit is that, if the string to split on is at the beginning/end of the string to be split, the results contain an empty string at that end:

'something cat'.split('cat'); // ['something ', '']
'cat something'.split('cat'); // ['', ' something']
'cat'.split('cat') // ['', '']

Reference:

You can use regular expressions to search for multiple occurrences. But if the search term just wants to be any string, and not have to worry about regular expression escaping. You could use indexOf to create a simple count function. You can then use this inside reduce to sum.

 const arr1 = ["cat", "I love cats and I have many cats", "dog"]; function count(str, search) { let p = 0, c = 0; while (true) { i = str.indexOf(search, p); p = i + 1; if (i >= 0) c ++; else break; } return c; } console.log( arr1.reduce((a,v) => a += count(v, 'cat'), 0));

You can split on space to get words and then search for your word.

 const arr1 = ["cat", "I love cats and I have many cats", "dog"], searchWord = 'cat', frequency = arr1.reduce((count, str) => { const words = str.split(' '); const matchedWord = words.filter(word => word.includes(searchWord)); return count + matchedWord.length; },0); console.log(frequency);

You can use regex match to find all the matches, then count them to get the total length.

let count=0;
const arr1 = ["cat", "I love cats and I have many cats", "dog"]
arr1.forEach(s=>{count+=(s.match(/cat/g)||[]).length})
print(count)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM