Skip to content

Instantly share code, notes, and snippets.

@bunnyhawk
Created November 7, 2020 16:05
Show Gist options
  • Save bunnyhawk/99bd0f1888c43df7efceb5800539d8cd to your computer and use it in GitHub Desktop.
Save bunnyhawk/99bd0f1888c43df7efceb5800539d8cd to your computer and use it in GitHub Desktop.
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