count occurrences in javascript code example
Example 1: how to count occurences in an array with javascript
const arrToInstanceCountObj = arr => arr.reduce((obj, e) => {
obj[e] = (obj[e] || 0) + 1;
return obj;
}, {});
arrToInstanceCountObj(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'])
Example 2: how do i count the number of occurrences in a string javascript
function charCount(myChar, str) {
let count = 0;
for (let i = 0; i < str.length; i++)
if (str.charAt(i) == myChar)
count++
return count;
}