1.Sales report from a JSON file
BeginnerWrite sales.json containing [{"day":"Mon","amount":4200},{"day":"Tue","amount":3800},{"day":"Wed","amount":5100}] using writeFile, read it back, and print the total, the best day and the average (rounded to a whole number).
Show hint
JSON.stringify before writing, JSON.parse after reading, then reduce for the total and a loop or reduce for the best day.
Show solution
import { readFile, writeFile } from "node:fs/promises";
await writeFile("sales.json", JSON.stringify([
{ day: "Mon", amount: 4200 },
{ day: "Tue", amount: 3800 },
{ day: "Wed", amount: 5100 },
]));
const sales = JSON.parse(await readFile("sales.json", "utf8"));
const total = sales.reduce((sum, s) => sum + s.amount, 0);
const best = sales.reduce((a, b) => (b.amount > a.amount ? b : a));
console.log("Total:", total);
console.log("Best day:", best.day, best.amount);
console.log("Average:", Math.round(total / sales.length));Total: 13100
Best day: Wed 5100
Average: 4367