The challenge
Write report(items) that takes items like { name: "rice", price: 40, qty: 2 } and returns { count, total, priciest }: how many items there are, the total cost (price × qty), and the name of the item with the highest price.
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
report([{ name: "rice", price: 40, qty: 2 }, { name: "fish", price: 60, qty: 1 }, { name: "salt", price: 2, qty: 3 }])gives{ count: 3, total: 146, priciest: "fish" }report([{ name: "pen", price: 2, qty: 5 }])gives{ count: 1, total: 10, priciest: "pen" }
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
One loop can do all three jobs.
Hint 2
Track the priciest item, not just its price, so you can return its name.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function report(items) {
let total = 0;
let priciest = items[0];
for (const item of items) {
total += item.price * item.qty;
if (item.price > priciest.price) priciest = item;
}
return { count: items.length, total, priciest: priciest.name };
}
Learn what you need
This exercise uses what Grade 8: Objects: Describing Things With Labels teaches. Read those notes first if any of it is new.