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.

+3


source to share


4 answers


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>
      

Run codeHide result


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>
      

Run codeHide result


+11


source


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);
      

Run codeHide result


+3


source


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)
      

Run codeHide result


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);
      

Run codeHide result


+1


source


The es6 single line uses String.prototype.match ()

const count = (str, ch) => (str.match(new RegExp(ch, 'g')) || []).length;

console.log(count('abcdefgaaa', 'a'));
      

Run codeHide result


+1


source







All Articles