Reputation: 787
I have the following array:
[
{
baseAsset: 'XRP',
quoteAsset: 'ETH',
quoteAssetPrecision: 6,
baseAssetPrecision: 8,
price: '0.00025170'
},
{
baseAsset: 'MOD',
quoteAsset: 'BTC',
quoteAssetPrecision: 8,
baseAssetPrecision: 4,
price: '0.00004280'
},
{
baseAsset: 'MOD',
quoteAsset: 'ETH',
quoteAssetPrecision: 8,
baseAssetPrecision: 4,
price: '0.00116700'
},
{
baseAsset: 'ENJ',
quoteAsset: 'BTC',
quoteAssetPrecision: 8,
baseAssetPrecision: 8,
price: '0.00004508'
},
{
baseAsset: 'ENJ',
quoteAsset: 'ETH',
quoteAssetPrecision: 6,
baseAssetPrecision: 8,
price: '0.00064370'
},
{
baseAsset: 'STORJ',
quoteAsset: 'BTC',
quoteAssetPrecision: 8,
baseAssetPrecision: 8,
price: '0.00002090'
},
{
baseAsset: 'STORJ',
quoteAsset: 'ETH',
quoteAssetPrecision: 6,
baseAssetPrecision: 8,
price: '0.00029910'
}
]
What I want to get:
[
{
ticker: 'XRP',
precision: 8,
},
{
ticker: 'MOD',
precision: 4,
},
{
ticker: 'BTC',
precision: 8,
},
{
ticker: 'ENJ',
precision: 8,
},
{
ticker: 'STORJ',
precision: 8,
},
{
ticker: 'ETH',
precision: 6,
}
]
As you can see, each precision
prop is associated with an asset and isn't changed. I want to extract each currency and its precision
from my array of currency pairs. What an elegant solution can be provided via lodash
? Other options are accepted. I was trying to implement this using native javascript, but solution didn't satisfied me:
const currenciesFetched = tradingPairsWithPrices
.flatMap((pair) => [
{
ticker: pair.baseAsset,
precision: pair.baseAssetPrecision,
},
{
ticker: pair.quoteAsset,
precision: pair.quoteAssetPrecision,
},
])
.filter((v, i, a) => {
return a.findIndex((t) => t.ticker === v.ticker) === i
})
Any ideas?
Upvotes: 0
Views: 65
Reputation: 23705
So if the goal to get uniq combination of ticker
+ precision
and we don't expect(so don't handle) the cases when there are different precision
for the same ticker
, then I think the easiest way just to use native {}
as a collector(or Set
as more specified alternative):
const accumulator = {};
tradingPairsWithPrices.forEach(pair => {
accumulator[pair.baseAsset] = pair.baseAssetPrecision;
accumulator[pair.quoteAsset] = pair.quoteAssetPrecision;
});
return accumulator
.entries()
.map(([ticker, precision]) => ({ ticker, precision }));
It's still possible to achieve this with lodash:
_.chain(traidingPairsWithPrices)
.flatMap(splitBaseAndQuote) // as you already do
.uniqBy('ticker')
.value()
If you have a long long list with a lot of entries per each ticker
value then first approach will be somehow faster. But probably, not that significantly.
Upvotes: 1