DEV Community

Discussion on: Javascript Algorithms Challenges | Part 2

Collapse
 
joelnet profile image
JavaScript Joel • Edited

A solution using reduce:

// Note: this function (like the original) does not take into consideration a tie.
const charCountHashTable = (str = '') =>
  Array.prototype.reduce.call(str, (acc, x) => {
    // increment count
    acc.count[x] = ~~acc.count[x] + 1

    // set 'most' to larger value
    acc.most = acc.count[x] > ~~acc.count[acc.most] ? x : acc.most

    return acc
  }, { count: {}, most: null })

charCountHashTable('lollipop')
//=> { count: { l: 3, o: 2, i: 1, p: 2}, most: 'l' } }