Code Lab

Count balls by color

MediumMap and Set10 min

Write a function countColors(balls) that counts the balls of each color and returns the result as one string.

  • balls is an array of color names, one per ball. Every name is in lower case. A name can have a space inside, for example 'light blue'.
  • For every color, write the name, one space and the count: 'blue 3'.
  • Join the parts with a comma and a space: 'blue 3, red 5, indigo 7'. There is no comma at the end.
  • Colors go in the order of their first appearance in balls. Do not sort them.
  • For an empty array return ''.

A map keeps keys in the order you add them, so it is a good place for the counts.

Examples

countColors(['blue', 'red', 'blue'])

Returns 'blue 2, red 1'

countColors(['red', 'red', 'green', 'red'])

Returns 'red 3, green 1'

countColors([])

Returns ''

Asked at emids · Source

Loading the editor...
  1. InputcountColors([ 'blue', 'red', 'indigo', 'red', 'blue', 'indigo', 'red', 'indigo', 'blue', 'indigo', 'red', 'indigo', 'red', 'indigo', 'indigo' ])
    Expected'blue 3, red 5, indigo 7'
  2. InputcountColors([ 'red', 'blue', 'red' ])
    Expected'red 2, blue 1'

Hidden tests run on Submit.