javascript Count the frequency of a value in an array
const countOccurrences = arr => arr.reduce((prev, curr) => (prev[curr] = ++prev[curr] || 1, prev), {});
// Examples
countOccurrences([2, 1, 3, 3, 2, 3]); // { '1': 1, '2': 2, '3': 3 }
countOccurrences(['a', 'b', 'a', 'c', 'a', 'b']); // { 'a': 3, 'b': 2, 'c': 1 }Array.prototype.frequencies = function() {
var l = this.length, result = {all:[]};
while (l--){
result[this[l]] = result[this[l]] ? ++result[this[l]] : 1;
}
// all pairs (label, frequencies) to an array of arrays(2)
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]); //=> 5
// or
var freqs = '1,1,2,one,one,2,2,22,three,four,five,three,three,five'
.split(',')
.frequencies();
alert(freqs.three); //=> 3
Also in JavaScript:
- devtools failed to load sourcemap when debugging react native
- Javascript singly linked list
- select input by name javascript
- check browser locale javascript
- Javascript compare two arrays
- delete session javascript
- palindrome string js
- Javascript remove array item by value
- how to find the smallest two numbers in an array javascript
- csv export in react
- abstraction in javascript
- moving a item fro index to another index, javascript
- simple counter react
- js database connection
- javascript replace without replace()
- swap function javascript
- toggle jquery remove others
- package json proxy
- nest winston
- text background fabricjs
- drawer navigation set width react native
- javascript string first letter lowercase
- js add animation to element
- ionic modal navbar not showing