Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 / lodash count 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 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.

like image 589
danday74 Avatar asked Jul 30 '17 22:07

danday74


People also ask

How do you count specific occurrences of characters in a string?

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.

How do you count occurrences in a string?

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.

How do you count the occurrence of a given character in a string JavaScript?

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.

How do you count occurrences in JavaScript?

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.


2 Answers

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>
like image 116
Sergey Karavaev Avatar answered Sep 18 '22 08:09

Sergey Karavaev


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);
like image 20
Ori Drori Avatar answered Sep 22 '22 08:09

Ori Drori