Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
24,162 PointsLearning.
That's why.

Steven Parker
220,425 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
26,680 PointsI was looking for best practices. It doesn't mean you can do it, you should do it.

Steven Parker
220,425 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.