1const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
2
3// Examples
4countOccurrences([2, 1, 3, 3, 2, 3], 2); // 2
5countOccurrences(['a', 'b', 'a', 'c', 'a', 'b'], 'a'); // 3
1// This function counts instances of elements in an array
2// the return object has the array elements as keys
3// and number of occurrences as it's value
4const arrToInstanceCountObj = arr => arr.reduce((obj, e) => {
5 obj[e] = (obj[e] || 0) + 1;
6 return obj;
7}, {});
8
9arrToInstanceCountObj(['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'])
10/*
11 {
12 h: 1,
13 e: 1,
14 l: 3,
15 o: 2,
16 w: 1,
17 r: 1,
18 d: 1,
19 }
20*/
1Array.prototype.frequencies = function() {
2 var l = this.length, result = {all:[]};
3 while (l--){
4 result[this[l]] = result[this[l]] ? ++result[this[l]] : 1;
5 }
6 // all pairs (label, frequencies) to an array of arrays(2)
7 for (var l in result){
8 if (result.hasOwnProperty(l) && l !== 'all'){
9 result.all.push([ l,result[l] ]);
10 }
11 }
12 return result;
13};
14
15var freqs = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].frequencies();
16alert(freqs[2]); //=> 5
17// or
18var freqs = '1,1,2,one,one,2,2,22,three,four,five,three,three,five'
19 .split(',')
20 .frequencies();
21alert(freqs.three); //=> 3