count the occurrences of something in a list/array 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: 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');