Bummer! You must be logged in to access this page.

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

filter() + reduce() operation fails

In this question:

Using the filter and reduce methods on the purchaseItems array, add the total price of all the groceries (items with a dept. of groceries). Store the total price in the groceryTotal variable. The correct amount can be seen in the comments below.

I've tried this answer, which failed:

groceryTotal = purchaseItem
  .filter( (items)=> items.dept === 'groceries')
  .reduce( (sum, items)=> sum + items.price, 0);

Why did it fail?

Please include the purchaseItems array. Might be you are just missing the 's' - doesn't it say purchaseItems array not purchaseItem array?

4 Answers

Steven Parker
Steven Parker
243,318 Points

You wrote "purchaseItem" (singular), but the name of the array is "purchaseItems" (plural).

Otherwise, the code looks good. :+1:

It's important to use strictly equal (===). I returned the total of the whole array without it.

This code works:

groceryTotal = purchaseItems
  .filter(total => total.dept === 'groceries')
  .reduce((sum, total) => sum + total.price, 0);

console.log(groceryTotal);

Cheers!

Steven Parker
Steven Parker
243,318 Points

The "strictly equal" operator is not necessary when comparing to a non-empty literal (but it won't hurt).

with syntax highlighting and clearer variable names:

groceryTotal = purchaseItems
  .filter(item => item.dept === 'groceries')
  .reduce((sum, item) => sum + item.price, 0);

Why does this code not work when I add the .toFixed

 groceryTotal = purchaseItems
  .filter(purchaseItem => purchaseItem.dept === 'groceries')
  .reduce((sum, purchaseItem) => sum + purchaseItem.price, 0)
  .toFixed(2);
Steven Parker
Steven Parker
243,318 Points

Next time start a new question instead of asking one in an "answer" (otherwise only the original asker and folks who posted answers are likely to see it).

The problem here is that the challenge is expecting a numeric result, but .toFixed returns a string instead.