Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTony Brackins
28,766 PointsNested Data Challenge
I got it right. It worked.
However, I don't feel like I did it elegantly.
Please see my answer:
const customers = [
{
name: "Tyrone",
personal: {
age: 33,
hobbies: ["Bicycling", "Camping"]
}
},
{
name: "Elizabeth",
personal: {
age: 25,
hobbies: ["Guitar", "Reading", "Gardening"]
}
},
{
name: "Penny",
personal: {
age: 36,
hobbies: ["Comics", "Chess", "Legos"]
}
}
];
// hobbies should be: ["Bicycling", "Camping", "Guitar", "Reading", "Gardening", "Comics", "Chess", "Legos"]
// Write your code below
let hobbies;
hobbies = customers.reduce((bucket, customer)=>{
let eachHobbie = customer.personal.hobbies.map((hobby)=>{
return hobby
})
return bucket.concat(eachHobbie)
},[]);
1 Answer
Steven Parker
231,269 PointsYou're doing a bit of extra work using "map" and the intermediate variable, you can simplify it down to just this:
hobbies = customers.reduce((bucket, customer) => bucket.concat(customer.personal.hobbies), []);
Tony Brackins
28,766 PointsPerfect. thx!!
Michael Kristensen
Full Stack JavaScript Techdegree Graduate 26,251 PointsMichael Kristensen
Full Stack JavaScript Techdegree Graduate 26,251 PointsWhile the solution Steven Parker suggested, is definitely the more streamlines version, I think the solution that this chain of videos was trying to lead us to was:
Where you use .map() to iterate through the different layers, and then .reduce() the returned arrays.