课程: JavaScript Practice: Scope and Closures
Solution: Reduce data with a function - JavaScript教程
课程: JavaScript Practice: Scope and Closures
Solution: Reduce data with a function
- [Instructor] All right, so down here we have our outfit. This is an array of objects, each of which has its own name and price. But here's where the tricky part happens. We have a nested array here called inventory. And within these inventory entries, we need to go deeper. So we need to grab the price from each of these accessories. And then we have an even deeper level of nesting where we have a jewelry category and we need to grab the price from here. So what we need to do is we need to implement this outfitCost method, and we're going to be using it to return this reduce function. So let's go ahead and replace this here on Line 11. We're going to say outfit, which is our array, and our outfit.reduce is going to take in another function. This function takes in two parameters. The first is total and the second is item. And let's just go ahead and use an arrow function here. And this arrow function is going to point directly at a set of curly braces, and here we're going to test for a condition. So if our item has a field called inventory. So if inventory exists, then we need to iterate through this as well. So if there is an item.inventory, we need to call another function. So we'll say return outfitCost item.inventory + total. Then outside of here we're going to say return total + item.price. So now what we're doing is we're just iterating through our array. And if we need to call this outfitCost function again, we can do so recursively and this is going to return that value. So the final thing that we need to do here, and this is a little tricky, we need to add another parameter to our reduce function. We'll say comma zero. And what the zero means for us is that we're going to add every time to zero. This is our initial value. Let's go ahead and run our tests, and we should see that all of our tests are passing. It looks like our total is $804.