Sum from array values with similar key in JavaScript


Let’s say, here is an array that contains some data about the stocks sold and purchased by some company over a period of 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]
];

We want to write a function that takes in this data and returns an object of arrays with key as stock name (like ‘AAPL’, ‘MCD’) and value as array of two numbers, where the first element represents the total buy and second element represents the total sell. Therefore, the code for doing this will be −

Example

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, ind) => {
      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));

Output

The output in the console will be −

{
   AAPL: [ 200, 120 ],
   WMT: [ 50, 75 ],
   MCD: [ 135, 90 ],
   GOOG: [ 0, 10 ],
   DIS: [ 15, 0 ]
}

Updated on: 21-Aug-2020

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements