-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpenditure-analysis.js
37 lines (35 loc) · 1.37 KB
/
expenditure-analysis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Implement a function `calculateTotalSpentByCategory` which takes a list of transactions as parameter
and return a list of objects where each object is unique category-wise and has total price spent as its value.
Transaction - an object like { itemName, category, price, timestamp }.
Output - [{ category1 - total_amount_spent_on_category1 }, { category2 - total_amount_spent_on_category2 }]
*/
function calculateTotalSpentByCategory(transactions) {
if (transactions.length === 0) {
return [];
}
let ans = [];
// Store all the categories with their total price.
let categoryWithAmount = {};
for (let transaction of transactions) {
// Get the category of current item.
const category = transaction.category;
// If the category is repeated, increment the total amount.
if (categoryWithAmount[category]) {
categoryWithAmount[category] += transaction.price;
} else {
// If the category comes first time, update the amount with current price.
categoryWithAmount[category] = transaction.price;
}
}
// Iterate over all the categories, create an object of the category name with total amount
// and add it to the ans array.
for (let category in categoryWithAmount) {
ans.push({
category: category,
totalSpent: categoryWithAmount[category],
});
}
return ans;
}
module.exports = calculateTotalSpentByCategory;