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 Combining filter() and reduce()

Ioana Rusu
Ioana Rusu
9,599 Points

Help with this challenge

Hi,

I need help with this challenge as I cannot figure out how to select the right prices as dept of groceries. How should this code look ?

Got stuck with that.

Many thanks

app.js
const purchaseItems = [
    {
        name: 'apples',
        dept: 'groceries',
        price: 2.49
    },
    {
        name: 'bread',
        dept: 'groceries',
        price: 2.99
    },
    {
        name: 'batteries',
        dept: 'electronics',
        price: 5.80
    },
    {
        name: 'eggs',
        dept: 'groceries',
        price: 3.99
    },
    {
        name: 't-shirts',
        dept: 'apparel',
        price: 9.99
    }
];
let groceryTotal;

// groceryTotal should be: 9.47
// Write your code below

groceryTotal = purchaseItems
  .filter(item => item.price)
  .reduce((sum, item) => sum = item.price, 0);

1 Answer

Steven Parker
Steven Parker
231,268 Points

You're close, but your filter needs to select the *"items with a dept. of groceries". To do this, the argument needs to be a function that will return "true" when given an item in that department. Something like this:

  .filter(item => item.dept == 'groceries')

Then, the "reduce" function needs add to the sum instead of replacing it:

  .reduce((sum, item) => sum += item.price, 0);  // "+=" instead of just "="
Ioana Rusu
Ioana Rusu
9,599 Points

Oooh thanks again Steven. I have tried to select only the dept with groceries but not like that, I have tried the wrong way obviously !

I feel a little dumb asking for help almost every challenge :( Thanks again :)