使用Javascript查找数组的数量和总利润/亏损

时间:2020-05-25 14:25:52

标签: javascript arrays

我有以下数据来计算总卖/买数量以及利润/亏损,并且我正在使用JSONPath来计算数组。如何与本机JavaScript一起使用以查找数量总计和利润/亏损总额。

data[?(@.side === "buy")].qty
data[?(@.side === "sell")].qty
[
  {
    "price": 1373.1,
    "qty": 2,
    "side": "sell"
  },
  {
    "price": 1375.3,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1376,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1373.8,
    "qty": 1,
    "side": "sell"
  },
  {
    "price": 1363.7,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1361,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1357.9,
    "qty": 1,
    "side": "sell"
  },
  {
    "price": 1362.7,
    "qty": 1,
    "side": "sell"
  },
  {
    "price": 1362,
    "qty": 1,
    "side": "buy"
  } 

]

计算从最后一个数组开始到顶部。

2 个答案:

答案 0 :(得分:3)

您可以在数组上使用reduce

const data = [
  {
    "price": 1373.1,
    "qty": 2,
    "side": "sell"
  },
  {
    "price": 1375.3,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1376,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1373.8,
    "qty": 1,
    "side": "sell"
  },
  {
    "price": 1363.7,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1361,
    "qty": 1,
    "side": "buy"
  },
  {
    "price": 1357.9,
    "qty": 1,
    "side": "sell"
  },
  {
    "price": 1362.7,
    "qty": 1,
    "side": "sell"
  },
  {
    "price": 1362,
    "qty": 1,
    "side": "buy"
  } 

]

const profitFor = (data) => data.reduce((total, element) => {
  if (element.side === 'buy') {
    total += element.qty * element.price
  } else {
    total -= element.qty * element.price
  }
  return total
}, 0)

console.log(profitFor(data))

如果您知道如何破坏对象,则可以尝试执行以下操作以获取清晰的代码:


    const profitFor = (data) => data.reduce((total, {side, qty, price}) => {
      if (side === 'buy') {
        total += qty * price
      } else {
        total -= qty * price
      }
      return total
    }, 0)

答案 1 :(得分:1)

您可以使用Series

Array.prototype.reduce()
const src = [{"price":1373.1,"qty":2,"side":"sell"},{"price":1375.3,"qty":1,"side":"buy"},{"price":1376,"qty":1,"side":"buy"},{"price":1373.8,"qty":1,"side":"sell"},{"price":1363.7,"qty":1,"side":"buy"},{"price":1361,"qty":1,"side":"buy"},{"price":1357.9,"qty":1,"side":"sell"},{"price":1362.7,"qty":1,"side":"sell"},{"price":1362,"qty":1,"side":"buy"}]

result = src.reduce((r,{price,qty,side}) => ({
  qty: (r.qty||0)+qty, 
  sellTotal: (r.sellTotal||0)+(side == 'sell' ? qty : 0),
  buyTotal: (r.buyTotal||0)+(side == 'buy' ? qty : 0),
  profit: (r.profit||0)+price*qty*(side == 'sell' ? 1 : -1)
}) , {}) 

console.log(result)