I’m trying to calculate the average amount each customer has spent based on an array of purchase objects. Here’s the sample data:
const purchases = [
{ customer: "Alice", amount: 250 },
{ customer: "Bob", amount: 400 },
{ customer: "Alice", amount: 150 },
{ customer: "David", amount: 300 },
{ customer: "Bob", amount: 200 },
{ customer: "Charlie", amount: 100 },
{ customer: "David", amount: 100 }
];
Here’s what I have tried so far:
function averageAmountSpent(arr) {
const result = {};
arr.forEach(item => {
const customer = item.customer;
result[customer] = (result[customer] || 0) + item.amount;
});
const average = {};
for (const amount in result) {
if (result.hasOwnProperty(amount) && typeof amount === 'number') {
average[amount] = result[amount] / 2; // Not sure what to divide by
}
}
return average;
}
console.log(averageAmountSpent(purchases));
This gives me the total amount spent per customer, but I’m not sure how to calculate the average amount spent by each customer (i.e., total spent divided by number of times they made a purchase). How should I modify this code to return each customer along with their average spend?
What I’ve tried:
- I successfully grouped totals by customer.
- I don’t know how to count how many times each customer appears in the
array to compute the average.
What I want:
An object like this:
{
Alice: 200,
Bob: 300,
David: 200,
Charlie: 100
}
Each value should be the average of all amounts for that customer.
Any help or suggestions would be appreciated. Thanks!



