Tsallaka zuwa abun ciki
Justice Tech School

Practice: Group and Count

Use reduce to build a frequency map.

Example
const words = "the cat and the hat and the bat".split(" ");
const freq = words.reduce((m, w) => ((m[w] = (m[w] || 0) + 1), m), {});
console.log(Object.entries(freq).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])));

Result

[
  [ 'the', 3 ],
  [ 'and', 2 ],
  [ 'bat', 1 ],
  [ 'cat', 1 ],
  [ 'hat', 1 ]
]

Exercise

Split words.

text.(" ")

Quiz Test

What does the accumulator hold?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.