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: 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 3: javascript count occurrences in string
function countOccurences(string, word) {
return string.split(word).length - 1;
}
var text="We went down to the stall, then down to the river.";
var count=countOccurences(text,"down");
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);