Created
October 26, 2018 13:40
-
-
Save edwingustafson/4dae1e3c3f7e22cd09f9015ffcb34238 to your computer and use it in GitHub Desktop.
Immutable.JS groupBy example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Immutable from 'immutable'; | |
interface Place { | |
country: string; | |
stateOrProvince: string; | |
city: string; | |
} | |
const list: Immutable.List<Place> = Immutable.List<Place>([ | |
{country: 'USA', stateOrProvince: 'Michigan', city: 'Petoskey'}, | |
{country: 'USA', stateOrProvince: 'Michigan', city: 'Detroit'}, | |
{country: 'USA', stateOrProvince: 'Michigan', city: 'Cadillac'}, | |
{country: 'USA', stateOrProvince: 'Ohio', city: 'Akron'}, | |
{country: 'USA', stateOrProvince: 'Ohio', city: 'Dayton'}, | |
{country: 'Canada', stateOrProvince: 'Ontario', city: 'London'}, | |
{country: 'Mexico', stateOrProvince: 'Chihuahua', city: 'Juarez'}, | |
{country: 'Mexico', stateOrProvince: 'Chihuahua', city: 'Delicias'}, | |
]); | |
const BLANK = '-'; | |
const countryGrouper = (place: Place | undefined) => place ? place.country : BLANK; | |
const stateOrProvinceGrouper = (place: Place | undefined) => place ? place.stateOrProvince : BLANK; | |
const byCountry: Immutable.Map<string, Immutable.List<Place>> = Immutable.Map<string, Immutable.List<Place>>(list.groupBy(countryGrouper)); | |
const byCountryAndStateOrProvince: Immutable.Map<string, Immutable.Map<string, Place>> = Immutable.Map<string, Immutable.Map<string, Place>>(byCountry.map((places: Immutable.List<Place> | undefined) => places ? places.groupBy(stateOrProvinceGrouper) : Immutable.Map())); | |
byCountryAndStateOrProvince.forEach((byStateOrProvince: any , country: any) => { | |
console.log('Country', country); | |
byStateOrProvince.forEach((places: Immutable.List<Place>, stateOrProvince: string) => { | |
console.log('+ State or Province', stateOrProvince); | |
places.forEach((place: Place | undefined) => console.log('+ + Place', place ? place.city : BLANK); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment