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
Ben Os
20,008 Pointsfilter() + 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?
Ben Os
20,008 PointsIndeed Dave varmutant
4 Answers
Steven Parker
243,318 PointsYou wrote "purchaseItem" (singular), but the name of the array is "purchaseItems" (plural).
Otherwise, the code looks good.
Zach Freitag
20,341 PointsIt'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
243,318 PointsThe "strictly equal" operator is not necessary when comparing to a non-empty literal (but it won't hurt).
Noah Yasskin
23,947 Pointswith syntax highlighting and clearer variable names:
groceryTotal = purchaseItems
.filter(item => item.dept === 'groceries')
.reduce((sum, item) => sum + item.price, 0);
Nnanna Okoli
Front End Web Development Techdegree Graduate 19,181 PointsWhy 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
243,318 PointsNext 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.
Dave StSomeWhere
19,870 PointsDave StSomeWhere
19,870 PointsPlease include the purchaseItems array. Might be you are just missing the 's' - doesn't it say purchaseItems array not purchaseItem array?