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()

Anik Devaughn
Anik Devaughn
7,751 Points

Challenge Task 1: Using the filter and reduce methods on the purchaseItems array, add the total price of all the......

Please help !! My code: 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(items => items.price === 'groceries') .reduce((sum, items) => sum + items.price, 0) .toFixed(2);

console.log( groceryTotal);

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(items => items.price === 'groceries')
.reduce((sum, items) => sum + items.price, 0) 
.toFixed(2);

console.log( groceryTotal);

2 Answers

Steven Parker
Steven Parker
231,268 Points

I see a few issues:

  • the filter should examine the dept of the items instead of the price.
  • the total should be left as a number and not converted into a string (as toFixed does)
  • you don't need to log anything to the console
Anik Devaughn
Anik Devaughn
7,751 Points

Thanks, it working :)