Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum from array values with similar key in JavaScript
When working with arrays of data, you often need to group and sum values based on a common key. This article demonstrates how to sum array values with similar keys using JavaScript's reduce() method.
Let's say we have an array containing stock transaction data for a company over time:
const transactions = [
['AAPL', 'buy', 100],
['WMT', 'sell', 75],
['MCD', 'buy', 125],
['GOOG', 'sell', 10],
['AAPL', 'buy', 100],
['AAPL', 'sell', 100],
['AAPL', 'sell', 20],
['DIS', 'buy', 15],
['MCD', 'buy', 10],
['WMT', 'buy', 50],
['MCD', 'sell', 90]
];
console.log("Sample transactions:");
console.log(transactions.slice(0, 3)); // Show first 3 transactions
Sample transactions: [ [ 'AAPL', 'buy', 100 ], [ 'WMT', 'sell', 75 ], [ 'MCD', 'buy', 125 ] ]
We want to create a function that groups these transactions by stock symbol and calculates total buy and sell amounts for each stock.
Using reduce() to Group and Sum
The reduce() method is perfect for accumulating values based on keys. Here's our solution:
const transactions = [
['AAPL', 'buy', 100],
['WMT', 'sell', 75],
['MCD', 'buy', 125],
['GOOG', 'sell', 10],
['AAPL', 'buy', 100],
['AAPL', 'sell', 100],
['AAPL', 'sell', 20],
['DIS', 'buy', 15],
['MCD', 'buy', 10],
['WMT', 'buy', 50],
['MCD', 'sell', 90]
];
const digestTransactions = (arr) => {
return arr.reduce((acc, val) => {
const [stock, type, amount] = val;
if (acc[stock]) {
const [buy, sell] = acc[stock];
if (type === 'buy') {
acc[stock] = [buy + amount, sell];
} else {
acc[stock] = [buy, sell + amount];
}
} else {
if (type === 'buy') {
acc[stock] = [amount, 0];
} else {
acc[stock] = [0, amount];
}
}
return acc;
}, {});
};
console.log(digestTransactions(transactions));
{
AAPL: [ 200, 120 ],
WMT: [ 50, 75 ],
MCD: [ 135, 90 ],
GOOG: [ 0, 10 ],
DIS: [ 15, 0 ]
}
How It Works
The function processes each transaction using these steps:
-
Destructuring:
[stock, type, amount]extracts values from each transaction array - Key Check: If the stock already exists in accumulator, update its totals
- Type Check: Add amount to buy total (index 0) or sell total (index 1)
-
Initialization: For new stocks, create
[amount, 0]for buy or[0, amount]for sell
Alternative Approach with Object Methods
Here's a cleaner version using object property access:
const digestTransactionsClean = (arr) => {
return arr.reduce((acc, [stock, type, amount]) => {
if (!acc[stock]) {
acc[stock] = { buy: 0, sell: 0 };
}
acc[stock][type] += amount;
return acc;
}, {});
};
const result = digestTransactionsClean(transactions);
console.log(result);
// Convert to array format if needed
const convertToArrayFormat = (obj) => {
const converted = {};
for (let stock in obj) {
converted[stock] = [obj[stock].buy, obj[stock].sell];
}
return converted;
};
console.log("Array format:", convertToArrayFormat(result));
{ AAPL: { buy: 200, sell: 120 }, WMT: { buy: 50, sell: 75 }, MCD: { buy: 135, sell: 90 }, GOOG: { buy: 0, sell: 10 }, DIS: { buy: 15, sell: 0 } }
Array format: { AAPL: [ 200, 120 ], WMT: [ 50, 75 ], MCD: [ 135, 90 ], GOOG: [ 0, 10 ], DIS: [ 15, 0 ] }
Conclusion
The reduce() method is an excellent choice for grouping and summing array values by key. Use destructuring and conditional logic to build accumulated results efficiently for complex data processing tasks.
