Created
November 7, 2020 16:05
-
-
Save bunnyhawk/99bd0f1888c43df7efceb5800539d8cd to your computer and use it in GitHub Desktop.
This file contains 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
const counties = [ | |
{ name: 'Clackamas', state: 'Oregon', population: 380000 }, | |
{ name: 'King', state: 'Washington', population: 2000000 }, | |
{ name: 'Kitsap', state: 'Washington', population: 250000 }, | |
{ name: 'Multinomah', state: 'Oregon', population: 750000 }, | |
{ name: 'Snohomish', state: 'Washington', population: 720000 }, | |
{ name: 'Wasco', state: 'Oregon', population: 25000 }, | |
]; | |
const oldStateCountyMap = counties.reduce((acc, county) => { | |
const currentCounty = { name: county.name, population: county.population }; | |
if (acc[county.state]) { | |
acc[county.state] = acc[county.state].concat(currentCounty) | |
} else { | |
acc[county.state] = [currentCounty] | |
} | |
return acc; | |
}, {}); // Setting our initialValue as an object to map against | |
const newStateCountyMap = counties.reduce((acc, { name, state, population }) => { | |
const currentCounty = { name, population }; | |
acc[state] = acc[state] ? [...acc[state], currentCounty] : [currentCounty]; | |
return acc; | |
}, {}); | |
// Both return: | |
// { | |
// 'Oregon': [ | |
// { name: 'Multinomah', population: 750000 }, | |
// { name: 'Clackamas', population: 380000 }, | |
// { name: 'Wasco', population: 25000 }, | |
// ], | |
// 'Washington': [ | |
// { name: 'King', population: 2000000 }, | |
// { name: 'Snohomish', population: 720000 }, | |
// { name: 'Kitsap', population: 250000 }, | |
// ] | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment