How to use Array In Javascript
In this method, we will use JavaScript Array to get the chars and occurrences by converting the string in array and then apply JavaScript array methods.
Example: In this example, we will use array reduce to return an array that contains the chars and their occurrences.
let str = "w3wiki";
let strArray = str.split("");
// console.log(strArray)
let result = strArray.reduce((chars, ch) => {
if (!chars[ch]) {
chars[ch] = 1;
} else {
chars[ch] += 1;
}
// console.log(ch);
return chars;
}, []);
// console.log(result)
console.log(
"The occurrence of each letter in given string is:", result)
Output
The occurrence of each letter in given string is: [ G: 2, e: 4, k: 2, s: 2, f: 1, o: 1, r: 1 ]
JavaScript Program to Count the Occurrences of Each Character
This article will demonstrate different approaches for implementing a JavaScript program to count the occurrences of each character in a string. We will be given a string as input and we return the chars used with the number it occurred in that string.