Specify the report
We need products priced at least 20, their average price and a preview with a 10% discount. Start with three products at prices 10, 20 and 30. Which products should qualify, and should the original catalog change?
const products = [
{ name: "Pen", price: 10, category: "stationery" },
{ name: "Notebook", price: 20, category: "stationery" },
{ name: "Bag", price: 30, category: "accessories" }
];
const selected = products.filter((product) => product.price >= 20);
const sum = selected.reduce((total, product) => total + product.price, 0);
const average = selected.length === 0 ? null : sum / selected.length;
const discounted = selected.map((product) => ({
...product,
price: product.price * 0.9
}));
console.assert(average === 25);
console.assert(discounted[0].price === 18);
console.assert(products[1].price === 20);
The parentheses around the arrow's object literal make it an expression returned by the callback. Without them, braces start a function body. Filter creates a new array but its retained objects are still shared. Mapping to new object copies avoids changing the original prices in this shallow record shape.
Guided search
Use find for the first named product and some to ask whether any product matches a category. A missing find result is undefined; inspect it before reading price. To find the most expensive product, use a loop with an initially null best result and compare each price.
Independent lab
Produce a report of stationery products only. Return their names, average price and whether every selected price is nonnegative. State the behavior for no matching category.
Correction
The names are Pen and Notebook; the average is 15. Every selected price is nonnegative. For no matches, names is an empty array and average is null. Every alone returns true for that empty array; if the report requires products, separately check its length.
Review
The report assumes valid records. If a price is missing, silently including it can corrupt the sum. Decide where input validation belongs before treating this operation as a production report.