I am trying to get array with total buy and total sell. But, it looks very hard to find way.
I Iterate over array but, couldn't get any way to display sum of buy and sell with name.
const orders = [
['AAPL', 'buy', 100],
['GOOG', 'sell', 10],
['AAPL', 'buy', 100],
['AAPL', 'sell', 100],
['AAPL', 'sell', 20],
];
function transform(orders) {
const result = {};
orders.forEach(element => {
})
return result;
}
<div id="result"></div>
I want output like:
/*
result = {
// total_buy, total_sell
'AAPL': [ 200, 120 ],
'GOOG': [ 0, 10]
}
*/
Any help would be greatly appreciated.
Use Array.reduce and check for the second entry ( action ) to add the amount to the right position :
const orders = [
["AAPL", "buy", 100],
["GOOG", "sell", 10],
["AAPL", "buy", 100],
["AAPL", "sell", 100],
["AAPL", "sell", 20]
];
const result = orders.reduce((acc, [key, action, amount]) => {
acc[key] = acc[key] || [0, 0];
if (action === "buy") acc[key][0] += amount;
if (action === "sell") acc[key][1] += amount;
return acc;
}, {});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With