Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Combining filter() with reduce(), you can remove values from an array, using the results to compute some value. Get some practice with this combination.
Snippets from the Video
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 }
];
// Result: { name: 'paper towels', price: 6.99 }
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 }
];
// Result: 239.97
Resources
Creating an initial value for reduce
(Spoiler Alert! Continue reading only if you've watched the whole video!)
The following solution is NOT RECOMMENDED, but will hopefully offer some insight into how the reduce method works. To create an initial value for the first problem, I would have had to construct a dummy object with a price
property set to zero, so the highest
parameter would have had a price
property to read in the if
statement.
const product = products
.filter(product => product.price < 10)
.reduce((highest, product) => {
if (highest.price > product.price) {
return highest;
}
return product;
}, { price: 0 });
Someone else trying to understand my code might have been confused as to why a dummy object was there, and what purpose it served. In this case, it makes more sense to let reduce
initialize the highest
parameter with the first product from the array.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up