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 trial

JavaScript JavaScript Array Iteration Methods Combining Array Methods Nested Data and Additional Exploration

Nested 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)
},[]);

While 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:

hobbies = customers
  .map(customer => customer.personal)
    .map(personal => personal.hobbies)
      .map(hobby => hobby)
  .reduce((arr, innerHobbies) => [...arr, ...innerHobbies], []);

Where you use .map() to iterate through the different layers, and then .reduce() the returned arrays.

1 Answer

Steven Parker
Steven Parker
231,248 Points

You'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), []);

Perfect. thx!!