Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Array Iteration Methods Combining Array Methods Nested Data

Using the reduce method, extract all the customer hobbies into their own array. Store the hobbies in the hobbies array.

what is wrong with my code that it didn't work

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
.map(customer => customer.personal.hobbies.map(hobby => hobby))
    .reduce((arr, hobbies) => [...arr, ...hobbies], []);

1 Answer

Hey James, your code is pretty close, but there are a few things wrong.

First, you are probably getting the error Unexpected Token. This is because you are not actually setting your map call to a variable. The JavaScript interpreter sees a random "." and doesn't know what to do with it. You would need to use

hobbies = customers.map()...

Second, you are using map unnecessarily. You're mapping over the customers array, and attempting to return an array of map calls. This is confusing and not needed. The question only requires you to use reduce. Here is my code, and it works:

hobbies = customers.reduce((arr, curr) => [...arr, ...curr.personal.hobbies ], []);

I always use curr in my reduce calls because it stands for "current item" but it doesn't matter what you call it as long as it makes sense to you and your team members if you're in a professional environment.

As you can see, my code is basically identical to the reduce call in your code. So you did basically get it.

I hope this helps! Good luck.