Last active
December 14, 2020 00:53
-
-
Save brignano/b893c32f4d820d3be68a5bfd91f93fac 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 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fyi @alexwhitmore