Search code examples
arraysfunctional-programminglodash

how to calculate the item frequency into an sorted array from an array in lodash


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?


Solution

  • 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);

    https://playcode.io/1218479