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:
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!
You need to save the number of purchases in result
, not just the total. So make the values there objects with both count
and total
properties.
function averageAmountSpent(arr) {
const result = {};
arr.forEach(({
customer,
amount
}) => {
if (Object.hasOwn(result, customer)) {
result[customer].count++;
result[customer].total += amount;
} else {
result[customer] = {
count: 1,
total: amount
};
}
});
const average = {};
Object.entries(result).forEach(([customer, {
count,
total
}]) => average[customer] = total / count);
return average;
}
console.log(averageAmountSpent(purchases));
<script>
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 }
];
</script>