This would be cleaner with `#inject` instead of all these maps and flattens.