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 trialTomas 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,174 PointsLearning.
That's why.
Steven Parker
231,248 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
231,248 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.