1

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 !:)

3
  • 2
    What have you tried so far? Sounds like you want to use reduce :) Commented Apr 3, 2017 at 10:18
  • This has nothing to do with React FYI. Commented Apr 3, 2017 at 10:18
  • I use foreach and reduce but im getting some difficulties Commented Apr 3, 2017 at 10:27

5 Answers 5

2

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));
Sign up to request clarification or add additional context in comments.

6 Comments

I think this is the most understandable solution
Just to clarify, you are hard coding the whole tally variable. What if there would be much more than just Buy and Sell elements? You would just write them down by hand? Unfortunately it won't work effectively, but I agree, now it's much more readable because of less code.
@Kinduser There is no point making super dynamic code when the requirements don't call for it. When it comes to buying and selling, there aren't likely to be too many more sides that need to be added, so hard coding them makes sense for future maintainability. Your example will work too, but will take someone a while to understand if they come back to it in a years time (or if a new developer starts on the project).
@MichaelPeyper It's not that complicated as it seems to be. I'm also just a beginner, which 5 months of experience. Anyways - I just think that when someone is deciding to make a question on so, he is expecting a high quality solution and even if he doesn't understand it - it's a motivation to keep learning.
@Kinduser each to his own. I'll take readability over catering for non-existent requirements any day of the week. Also, it wouldn't take much to dynamically generate the tally object if such a requirement ever came about.
|
1

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);

7 Comments

Can we add the output values in a single object? Great answer btw
Like obj = {aSide: 4, bSide: 8, aPrice: 123, bPrice: 12}
@user7334203 I will try
Sorry for confusing you. is it too complex?
Awesome! Thanks a lot
|
1

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);

Comments

1

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;

Comments

0

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}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.