Count the words

Read a line of words, and count how often each one appears.

What to build

A tally built with an object, printed in the order the words were first seen.

Requirements

  • Treat words that differ only in capital letters as the same word.
  • Print each different word in lower case, followed by a space and its count.
  • Print the words in the order each word first appears.

Input

One line of words separated by single spaces.

Output

One line per different word.

Constraints

There are from 1 to 200 words, made of letters and digits only.

Example

Input:

the cat sat The

Output:

the 2
cat 1
sat 1

Why it works

An object finds a word's count directly by name, with no searching. A separate list keeps the order, because objects move number-like keys such as "10" to the front.

Examples

Example 1 · Input
the cat sat The
Expected output
the 2
cat 1
sat 1
Example 2 · Input
hello
Expected output
hello 1

Hints

Hint 1

Lower-case the line first: line.toLowerCase().

Hint 2

Use an object as a tally: counts[word] = (counts[word] ?? 0) + 1.

Hint 3

Object keys keep the order they were added in (for keys that are not numbers), so Object.entries gives first-seen order. To be safe with words such as "10", keep an array of the words in the order seen too.

Solution

Show one correct solution (try it yourself first)
const words = prompt().toLowerCase().split(" ");
const counts = {};
const order = [];
for (const w of words) {
  if (counts[w] === undefined) {
    counts[w] = 0;
    order.push(w);
  }
  counts[w]++;
}
for (const w of order) {
  console.log(w, counts[w]);
}

Lesson: Objects →