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

Melissa Benton
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Melissa Benton
Front End Web Development Techdegree Graduate 17,805 Points

How do I create an array of hobbies?

What am I missing in my code for it to iterate over all the object literals in the customers array and return the hobbies in their own array? As of now it's just returning the last object literal's hobbies in a new array.

app.js
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"]
    }
  }
];
let hobbies;

// hobbies should be: ["Bicycling", "Camping", "Guitar", "Reading", "Gardening", "Comics", "Chess", "Legos"]
// Write your code below

hobbies = customers.reduce((hobbyArr, user) => {
  hobbyArr = user.personal.hobbies;
  return hobbyArr;
}, []);

1 Answer

Steven Parker
Steven Parker
231,236 Points

You're close, but right now hobbyArr is being replaced with the hobbies for each customer:

  hobbyArr = user.personal.hobbies;

So the final result is an array with just the hobbies of the last customer.

Modify the function to make it accumulate the hobbies into a larger list instead.

Hint: spread syntax might be useful here!