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

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.