I want to count the number of occurrences of a character in a string.
This stack overflow post does that using ES5 but not ES6 or Lodash:
Count the number of occurrences of a character in a string in Javascript
However, I want to know if there is a more ES6 way of doing this. Lodash solutions are also acceptable.
Approach: 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.
match() One of the solution can be provided by the match() function, which is used to generate all the occurrences of a string in an array. By counting the array size that returns the number of times the substring present in a string.
In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.
And here's a lodash solution:
const count = (str, ch) => _.countBy(str)[ch] || 0;
console.log(count("abcadea", "a"));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
The solution looks compact, does not use regular expressions and still does the job in a single scan. It must be quite fast, though if the performance is really crucial, better opt for good old for
loop.
Update: Another lodash-based solution:
const count = (str, ch) => _.sumBy(str, x => x === ch)
console.log(count("abcadea", "a"));
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
I don't think that it's better than the RegExp solutions, but it's ES6.
Spread the string to and array, and filter the result to get only the letter that you want. The length of the resulting array is the number off occurrences of that letter.
const str = "aabbccaaaaaaaccc";
const result = [...str].filter(l => l === 'c').length;
console.log(result);
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