【发布时间】:2017-08-26 13:11:25
【问题描述】:
我有一系列跨不同货币和交易所的外汇交易:
[
{buyCurr: "USD", sellCurr: "CAD", exchange: "Canada", buyunits: 1000, sellunits: 1200},
{buyCurr: "EUR", sellCurr: "CAD", exchange: "Europe", buyunits: 10000, sellunits: 15000},
{buyCurr: "GBP", sellCurr: "USD", exchange: "NYSE", buyunits: 5000, sellunits: 8000},
{buyCurr: "USD", sellCurr: "INR", exchange: "BSE", buyunits: 3000, sellunits: 180000},
{buyCurr: "USD", sellCurr: "JPY", exchange: "Japan", buyunits: 32000, sellunits: 1000000},
{buyCurr: "RUB", sellCurr: "INR", exchange: "Russia", buyunits: 1000, sellunits: 1100},
{buyCurr: "USD", sellCurr: "CNY", exchange: "China", buyunits: 3000, sellunits: 18000},
{buyCurr: "CNY", sellCurr: "INR", exchange: "China", buyunits: 10000, sellunits: 100000},
{buyCurr: "USD", sellCurr: "CAD", exchange: "Canada", buyunits: 1000, sellunits: 1200},
{buyCurr: "EUR", sellCurr: "CAD", exchange: "Europe", buyunits: 10000, sellunits: 15000},
{buyCurr: "GBP", sellCurr: "USD", exchange: "NYSE", buyunits: 5000, sellunits: 8000},
{buyCurr: "USD", sellCurr: "INR", exchange: "BSE", buyunits: 3000, sellunits: 180000},
{buyCurr: "USD", sellCurr: "JPY", exchange: "Japan", buyunits: 32000, sellunits: 1000000},
{buyCurr: "RUB", sellCurr: "INR", exchange: "Russia", buyunits: 1000, sellunits: 1100},
{buyCurr: "USD", sellCurr: "CNY", exchange: "China", buyunits: 3000, sellunits: 18000},
{buyCurr: "CNY", sellCurr: "INR", exchange: "China", buyunits: 10000, sellunits: 100000},
]
我想总结一下我在交易所和货币方面的头寸。所以结果看起来像:
[{
curency : USD,
exchange: Canada,
units: 2000
},
{
curency : CAD,
exchange: Canada,
units: -2400
},
{
curency : USD,
exchange: NYSE,
units: -12000
},
......and so on
]
交易所的单位数量是(货币买入单位的总和(i))-(卖出单位的总和(i))。 SO USD 将仅对 USD 进行抵消。
我想出的一种方法是使用 forEach 遍历每个实例,过滤属性并添加/减少 buyCurr 和 sellCurr。
我也试过 lodash,但它只能让我做 groupBy 一个属性。
在 javascript 中是否有更好/更有效的方法?
【问题讨论】:
-
一个循环怎么样?
-
我尝试使用 forEach 但代码变得很长,所以希望有更好的方法在 javascript 中执行它,因为这似乎是一个常见问题。
-
您的结果不清楚:
CAD Canada -2400是如何计算的?2000 - 2400as ((buyunits 的总和) - (sellunits 的总和)) 不等于-2400 -
我更新了预期的输出。一种货币只能被同一种货币抵消。所以只能从美元中减去美元。在上述情况下,我只在 CAD 上进行了两次卖出交易,以换取 1200 美元的“加拿大”,因此单位 = -1200-1200 = -2400。
标签: javascript lodash javascript-objects