Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum from array JavaScript

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.

like image 227
ketan Avatar asked Aug 01 '26 19:08

ketan


1 Answers

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);
like image 72
Taki Avatar answered Aug 04 '26 10:08

Taki