Use a for loop over parallel arrays to compute a running total across several items.
You start with:
const items: string[] = ["Shirt", "Pants", "Shoes", "Hat"];
const prices: number[] = [25, 40, 60, 15];
const quantities: number[] = [2, 1, 1, 3];
Build:
Shirt x2: $50 Pants x1: $40 Shoes x1: $60 Hat x3: $45 Total: $195
Rules:
- For each index
i, the item's subtotal isprices[i] * quantities[i]. - Build one line per item, in order, in the format
"Name xQ: $subtotal"(e.g."Shirt x2: $50"). - Add every subtotal to a running
total. - Finish with a
"Total: $..."line. - Join all the lines with a newline
"\n"into one stringresult, then print it withconsole.log(result).
Start with
const lines: string[] = []; let total = 0; before the loop, then push each formatted line and add to total.
Call
lines.join("\n") at the end.
const items: string[] = ["Shirt", "Pants", "Shoes", "Hat"];
const prices: number[] = [25, 40, 60, 15];
const quantities: number[] = [2, 1, 1, 3];
const lines: string[] = [];
let total: number = 0;
for (let i = 0; i < items.length; i++) {
const sub: number = prices[i] * quantities[i];
total = total + sub;
lines.push(items[i] + " x" + quantities[i] + ": $" + sub);
}
lines.push("Total: $" + total);
const result: string = lines.join("\n");
console.log(result);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
