Scriptdrill

Level 4: Data shaping Exercise 29 of 45 Pro

Totals per customer

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Each order looks like `{ customer, items: [{ price, qty }] }`. Return an object mapping each customer to the total of all their orders, where an item is worth `price * qty`. A customer whose orders have no items still appears, with 0. Prices can be negative (a discount line).

What this exercise teaches

The inner reduce with a 0 start value turns an empty item list into 0, and `(totals[c] || 0) + subtotal` creates or extends the customer's total, so every customer appears exactly once.

A hint if you get stuck

Loop over the orders. For each one, `reduce` its items into a subtotal starting from `0`, then add it to `totals[order.customer]`, which starts at `0` too.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Data shaping