I have an object with keys representing country shortcodes and values representing a count. I would like to iterate through this object and return an array of countries with the highest counts. I’m new to Coffeescript and unsure of the most elegant way to handle this. Any help is most appreciated. Thanks!
With the below data as an example I would like for the array to return ['AU', 'US', 'BR', 'CN', 'IN']
vacation_spots = {
AU: 3,
BR: 2,
CF: 1,
CN: 2,
IN: 2,
MX: 1,
SD: 1,
TD: 1,
TM: 1,
US: 3
}
get_top_5(vacation_spots)
get_top_5 = (items) ->
for k, v of items
# ?
Using vanilla JS Array methods:
You can compress it all into one expression like
(k for k of items).sort((a, b) -> items[b] - items[a])[...5]but i think separating each step reads a bit better.The sort step sorts the country codes by their value on the
itemsobject; it uses theArray::sortmethod, which expects a comparator function that takes two arguments and returns an integer. If you have Underscore.js included, i’d recommend using_.sortBy, which uses comparator function that just takes one argument and returns a comparable object:Edit: Also, instead of
(k for k of items)you can useObject.keys(items)(beware, IE <9 will not support it) or_.keys(items), both of which will compile to much more compact JS code than the loop.