Example 1: javascript Count the occurrences of a value in an array
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([2, 1, 3, 3, 2, 3], 2);
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a');
Example 2: 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 3: 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;
}
Example 4: javascript Count the frequency of a value in an array
const countOccurrences = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {});
countOccurrences([2, 1, 3, 3, 2, 3]);
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']);
Example 5: count number of times an element is occuring in an array in javascript
Array.prototype.frequencies = function() {
var l = this.length, result = {all:[]};
while (l--){
result[this[l]] = result[this[l]] ? ++result[this[l]] : 1;
}
for (var l in result){
if (result.hasOwnProperty(l) && l !== 'all'){
result.all.push([ l,result[l] ]);
}
}
return result;
};
var freqs = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].frequencies();
alert(freqs[2]);
var freqs = '1,1,2,one,one,2,2,22,three,four,five,three,three,five'
.split(',')
.frequencies();
alert(freqs.three);