How to use Array.reduce() In Javascript
Using Array.reduce(), convert the string to an array of characters and accumulate the count of occurrences of the specific character by incrementing the accumulator for each occurrence found during iteration.
Example: In this example The function countOccurrences
takes a string str
and a character char
, counts occurrences of char
in str
, using the spread operator and reduce
function countOccurrences(str, char) {
return [...str].reduce((count, currentChar) =>
currentChar === char ? count + 1 : count, 0);
}
console.log(countOccurrences("hello world", "o"));
Output
2
JavaScript Program to Count the Occurrences of a Specific Character in a String
In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript.
Example:
Input : S = “w3wiki” and c = ‘e’
Output : 4
Explanation: ‘e’ appears four times in str.
Input : S = “abccdefgaa” and c = ‘a’
Output : 3
Explanation: ‘a’ appears three times in str.
We will explore every approach to counting the occurrences of a specific character in a string, along with understanding their basic implementations.
Table of Content
- Using for loop
- Using split() Method
- Using match() Method
- Using Array.reduce()
Contact Us