Skip to content

Instantly share code, notes, and snippets.

@brignano
Last active December 14, 2020 00:53
Show Gist options
  • Save brignano/b893c32f4d820d3be68a5bfd91f93fac to your computer and use it in GitHub Desktop.
Save brignano/b893c32f4d820d3be68a5bfd91f93fac to your computer and use it in GitHub Desktop.
const parks = [
{
name: 'Canyonlands',
areaInSquareKm: 1366.2,
location: { state: 'Utah' },
},
{
name: 'Crater Lake',
areaInSquareKm: 741.5,
location: { state: 'Oregon' },
},
{
name: 'Zion',
areaInSquareKm: 595.9,
location: { state: 'Utah' },
},
];
//create function, parkNameAndState(parks), use reduce method
//return an object where the keys are the name of the states
// and the values will be an array of each park associated with that state
function parkNameAndState(parks) {
return parks.reduce(function (stateParks, park) {
if (!stateParks[park.location.state]) { // for the first occurrence of a state we have to create a new array
stateParks[park.location.state] = new Array();
}
stateParks[park.location.state].push(park.name); // push the park name to our array with where key is state
return stateParks;
},
[] // initialize stateParks as empty array
);
}
// proof of concept
console.log(parkNameAndState(parks));
@brignano
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment