ES6 / lodash counts the number of occurrences of a character in a string
I want to count the number of occurrences of a character in a string.
This column uses 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 an ES6 way to do this. Lodash solutions are also acceptable.
source to share
And here is lodash's 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, doesn't use regular expressions, and still does the job in a single scan. This should be pretty fast, although if performance is really important, go for the good old loop for
.
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>
source to share
I don't think it is better than RegExp solutions, but this is ES6.
Allocate the string and array and filter the result to get only the letter you want. The length of the resulting array is the misspelled number in this letter.
const str = "aabbccaaaaaaaccc";
const result = [...str].filter(l => l === 'c').length;
console.log(result);
source to share
You can use the constructor Array.from()
, RegExp
andString.prototype.match()
const str = "abcabc";
const occurences = Array.from(str, (s, index) =>
({[s]:str.match(new RegExp(s, "g")).length, index}));
console.log(occurences)
If the requirement is only to count occurrences
symbol
you can use a loop for..of
with statements ===
, &&
and++
const [str, char] = ["abc abc", " "];
let occurrences = 0;
for (const s of str) s === char && ++occurrences; // match space character
console.log(occurrences);
source to share
The es6 single line uses String.prototype.match ()
const count = (str, ch) => (str.match(new RegExp(ch, 'g')) || []).length;
console.log(count('abcdefgaaa', 'a'));
source to share