How do you calculate the total price of active products with chaining in JavaScript?
products.filter(p => p.active).map(p => p.price).reduce((acc, price) => acc + price, 0). Filter active products, extract prices, sum them.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Chaining map, filter, and reduce in JavaScript
Yes. map and filter return new arrays, so you can chain them. reduce returns a single value, so it is usually last. Example: arr.filter(n => n > 1).map(n => n * 2).reduce((a, b) => a + b, 0).
Because reduce returns a single value (not an array), so you cannot chain array methods after it. map and filter return arrays, so they can be chained. reduce is the final step that combines everything.
Each chain step creates a new array (multiple passes). For large arrays, a single reduce or loop may be faster. But chaining is more readable. Optimize only if profiling shows a problem.
Still have questions?
Browse all our FAQs or reach out to our support team
