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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Tomas Svojanovsky](https://secure.gravatar.com/avatar/ef07f01fa4ae404276da89768c74851b?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Tomas Svojanovsky
26,680 PointsWhy should I solve this way?
Hello, the task I need to solve sum of products over price 10.
I find my solution
const products = [
{ name: 'hard drive', price: 59.99 },
{ name: 'lighbulbs', price: 2.59 },
{ name: 'paper towels', price: 6.99 },
{ name: 'flatscreen monitor', price: 159.99 },
{ name: 'cable ties', price: 19.99 },
{ name: 'ballpoint pens', price: 4.49 },
];
const total = products
.reduce((sum, product) => {
if (product.price > 10) {
return sum + product.price;
}
return sum;
}, 0)
.toFixed(2);
I think my solution is faster, but with filter is cleaner.
3 Answers
![Tom Geraghty](https://uploads.teamtreehouse.com/production/profile-photos/1155052/micro_thisone_copy.jpg)
Tom Geraghty
24,174 PointsLearning.
That's why.
![Steven Parker](https://uploads.teamtreehouse.com/production/profile-photos/969492/micro_tool_chess_set_2.jpg)
Steven Parker
230,688 PointsContratulations, you re-invented "filter". And yes, it is a bit faster.
But if you were going purely for efficiency, a good ol' "for" loop would be even better:
let sum = 0;
for (let i = 0; i < products.length; i++) {
if (products[i].price > 10) sum += products[i].price;
}
const total = sum.toFixed(2);
But the purpose of the exercise was not to write the fastest code, but to practice the use of these array methods.
![Tomas Svojanovsky](https://secure.gravatar.com/avatar/ef07f01fa4ae404276da89768c74851b?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Tomas Svojanovsky
26,680 PointsI was looking for best practices. It doesn't mean you can do it, you should do it.
![Steven Parker](https://uploads.teamtreehouse.com/production/profile-photos/969492/micro_tool_chess_set_2.jpg)
Steven Parker
230,688 PointsI don't think the choice of method falls into the "best practices" category. Both ways do the job and the code is easy to read and maintain.