2

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?

Enlico
  • 23,259
  • 6
  • 48
  • 102
user824624
  • 7,077
  • 27
  • 106
  • 183
  • 1
    As someone who has well over 6000 reputation points, you should probably know how the search function on SO works ... For the counting part https://stackoverflow.com/questions/5667888/counting-the-occurrences-frequency-of-array-elements (probably you need slight adaptions to create a resulting array) – derpirscher Feb 22 '23 at 08:18
  • 1
    And for the sorting part https://stackoverflow.com/questions/979256/sorting-an-array-of-objects-by-property-values – derpirscher Feb 22 '23 at 08:27

2 Answers2

1

_.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>
Enlico
  • 23,259
  • 6
  • 48
  • 102
0

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

Rob Hill
  • 24
  • 4