topThreeWords 4 kyu

by trentHarlem

JavaScript

function topThreeWords(text) {
  const input = text.split(' ')
  const words = input.reduce((occurrences, word) => {
    occurrences[word] = occurrences[word] && word!='' ? (occurrences[word] + 1) : 1;
    //console.log('occurrences', occurrences)
    //console.log('word', word)
    return occurrences;
  }, {});
  // const archive = Object.entries(words).map(a => a.sort((a, b) => b[1] - a[1]))
  const archive = Object.entries(words).map(a => a[1]).sort((a,b)=>b-a)
  console.log(archive)
   const getKeyByVal = (obj, val) =>
    Object.keys(obj).find(key => obj[key] === val);
    const output= []
for (let i=0; i<3;i++) {
output.push(getKeyByVal(words,archive[i]))
}
return output
  /*   function getValueByKey(object, row) {
    return object[row];
    }
    getValueByKey */
}

console.log(topThreeWords("a a a  b  c c  d d d d  e e e e e"), ['e','d','a'])
console.log(topThreeWords("a a c b b"), ['a','b','c'])
/* console.log(topThreeWords(`In a village of La Mancha, the name of which I have no desire to call to
mind, there lived not long since one of those gentlemen that keep a lance
in the lance-rack, an old buckler, a lean hack, and a greyhound for
coursing. An olla of rather more beef than mutton, a salad on most
nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra
on Sundays, made away with three-quarters of his income.`), ['a', 'of', 'on']) */