RamAlx
RamAlx

Reputation: 7344

Mapping through an array of objects in javascript

i have an array of objects like this:

[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ] 

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this: Buy = 3 AvgPrice for Buy = 120 Sell = 1 AvgPrice for Sell = 200 I'm new to javascript and react so i have some difficulties. Thanks !:)

Upvotes: 1

Views: 153

Answers (5)

kind user
kind user

Reputation: 41913

Simple solution using Array#forEach and Object.keys().

var arr = [{side: 'Buy', price: 100}, {side: 'Buy', price: 110}, {side: 'Sell', price: 200}, {side: 'Buy', price: 150}], obj = {}, res = [];

arr.forEach(function(v){
 (obj[v.side] || (obj[v.side] = [])).push(v.price);
});
var res = Object.keys(obj).reduce(function(s,a) {
  s[a] = obj[a].length;
  s['avg' + a] = obj[a].reduce((a,b) => a + b) / obj[a].length;
  return s;
}, {});
console.log(res);

Upvotes: 1

Raskolnikov
Raskolnikov

Reputation: 56

You can do it like this:

let arr = [{side: "Buy", price: 100}, {side: "Buy", price: 110}, {side:     "Sell", price: 200}, {side: "Buy", price: 150} ];
let buyPrices = [];
let sellPrices = [];
arr.forEach((item, index) => {
  if (item.side === 'Buy') {
    buyPrices.push(item.price);
  } else if (item.side === 'Sell') {
    sellPrices.push(item.price);
  }
});

let avgBuy = buyPrices.reduce((a, b) => a + b)/buyPrices.length;
console.log(`Buy -> ${buyPrices.length}
AvgBuyPrices -> ${avgBuy}`);
let avgSell = sellPrices.reduce((a, b) => a + b)/sellPrices.length;
console.log(`Sell -> ${sellPrices.length}
AvgSellPrices -> ${avgSell}`);

Upvotes: 0

Michael Peyper
Michael Peyper

Reputation: 6944

Probably easiest to just iterate the array and keep a rolling average for each side.

var data = [{side: 'Buy', price: 100}, {side: 'Buy', price: 110}, {side: 'Sell', price: 200}, {side: 'Buy', price: 150} ];

var tally = { Buy: { count: 0, total: 0 }, Sell: { count: 0, total: 0 } };

data.forEach(item => {
    tally[item.side].count = tally[item.side].count + 1;
    tally[item.side].total = tally[item.side].total + item.price;
})

console.log("AvgPrice for Buy = " + (tally.Buy.total / tall.Buy.count) + " Sell = 1 AvgPrice for Sell = " + (tally.Sell.total / tall.Sell.count));

Upvotes: 2

anis programmer
anis programmer

Reputation: 999

Please check this:

    var arrayBuySell=[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
var averageBuy = 0;
var averageSell = 0;
var totalbuy=0;
var totalbuycount=0;
var totalsellcount=0;
var totalsell=0;
for (var i = 0; i < arrayBuySell.length; i++) {
    if(arrayBuySell[i]="Buy")
      {
       totalbuy+=arrayBuySell[i].price;
       totalbuycount=arrayBuySell[i].price.Count();
      }
     else
      {
       totalsell+=arrayBuySell[i].price;
       totalsellcount=arrayBuySell[i].price.Count();
      }
  }
averageBuy =totalbuy/totalbuycount;
averageSell=totalsell/totalsellcount;

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104529

Use any iterator like forEach, for etc to iterate the data, and use two object variables, one will store the buy data and other will store sell data.

Write it like this:

var data = [{side: 'Buy', price: 100}, {side: 'Buy', price: 110}, {side: 'Sell', price: 200}, {side: 'Buy', price: 150} ];

var buy = {}, sell = {};

data.forEach(el => {
    if(el.side == 'Buy'){
          buy['count'] = (buy['count'] || 0) + 1;
          buy['total'] = (buy['total'] || 0) + el.price; 
    }else{
         sell['count'] = (sell['count'] || 0) + 1;
         sell['total'] = (sell['total'] || 0) + el.price; 
    }
})

console.log(buy.total/buy.count, sell.total/sell.count);

Upvotes: 1

Related Questions