I have an array like this:
['A', 'B', 'C', 'B', 'A', 'B', 'C', 'B', 'B']
I want to get a hashtable showing the [{'B':5}, {'A':2}, {'C':2}]
in sorted order of item frequency in lodash reduct or countBy, but don't know how to make it?
I have an array like this:
['A', 'B', 'C', 'B', 'A', 'B', 'C', 'B', 'B']
I want to get a hashtable showing the [{'B':5}, {'A':2}, {'C':2}]
in sorted order of item frequency in lodash reduct or countBy, but don't know how to make it?
_.countBy
is the way, but an object's fields are not sorted, so you have to transform it to a list of entries, via _.entries
, and then you can _.sortBy
the second element, i.e. the one you get via _.iteratee(1)
; finally you can _.reverse
:
console.log(
_.reverse(
_.sortBy(
_.entries(_.countBy([ 'A', 'B', 'C', 'B', 'A', 'B', 'C', 'B', 'B' ])),
_.iteratee(1))))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
Ok, an answer using lodash. Use the countBy method to get an object to hold the frequency of each item in the array. Next, use the toPairs method converting that object into an array of key-value pairs. finally, use orderBy to sort the array based on the frquency in descending order, and the item in ascending order
import {
countBy,
orderBy,
toPairs
} from 'lodash';
const theArray = ['A', 'B', 'C', 'B', 'A', 'B', 'C', 'B', 'B'];
var freqs = countBy(theArray);
var freqArray = orderBy(toPairs(freqs), ['1', '0'], ['desc', 'asc']);
console.log(freqArray);