javascript - 匹配对象数组中的对象键并返回键,具有最高音量值的值
问题描述
我有一个对象数组,baseAsset 键 和 Volume 是每个对象的一部分,但每个对象的体积是不同的。
我想匹配 baseAsset 键并返回具有最高音量值的对象。 效率和速度很重要,因为阵列有 3000 多个对象
let tickerA = [{
pair: 'AUDUSD',
baseAsset: 'AUD',
lastPriceUSD: 0.74,
volume: 1000
}, {
pair: 'AUDUSD',
baseAsset: 'AUD',
lastPriceUSD: 0.76,
volume: 2000
}, {
pair: 'USDEUR',
baseAsset: 'USD',
lastPriceUSD: 1.25,
volume: 1200
}, {
pair: 'USDEUR',
baseAsset: 'USD',
lastPriceUSD: 1.19,
volume: 1500
}]
函数的预期回报
tickerB = [{
baseAsset: 'AUD',
lastPriceUSD: 0.76,
volume: 2000
}, {
baseAsset: 'USD',
lastPriceUSD: 1.25,
volume: 1500
}]
解决方案
如果该项目的值大于该键的当前项目的值,则一种方法是迭代的值tickerA
并将它们映射到键:baseAsset
volume
baseAsset
let tickerA = [{
pair: 'AUDUSD',
baseAsset: 'AUD',
lastPriceUSD: 0.74,
volume: 1000
}, {
pair: 'AUDUSD',
baseAsset: 'AUD',
lastPriceUSD: 0.76,
volume: 2000
}, {
pair: 'USDEUR',
baseAsset: 'USD',
lastPriceUSD: 1.25,
volume: 1200
}, {
pair: 'USDEUR',
baseAsset: 'USD',
lastPriceUSD: 1.19,
volume: 1500
}];
/* Use map to relate baseAsset key of tickerA item with current max volume value */
const map = new Map()
/* Iterate tickerA items, searching for greatest volume value per baseAsset class */
for(const item of tickerA) {
const assetMatch = map.get(item.baseAsset);
if(assetMatch && item.volume < assetMatch.volume) {
/* If matching item (by asset found) with volume greater than that of current tickerA
item, then disregard the current item */
continue;
}
else {
/* Otherwise, this tickerA item is; the first of the asset class, or greater in volume
so we'll update the map entry for this asset class */
map.set(item.baseAsset, item);
}
}
/* Extract the map values as an array */
const tickerB = Array.from(map.values());
console.log(tickerB);
推荐阅读
- php - Woocommerce 订阅和账户资金插件之间的网关
- sql - 如何拆分作为具有可变长度的部分字符串部分编号的 SQL 列
- python - 如何使用熊猫数据框计算点之间的距离?
- javascript - 让 Discord 机器人命令不区分大小写?
- elasticsearch - 如何在 Elasticsearch 中存储商店产品
- sql - 如何在组合查询中编辑字段
- google-app-maker - 如何在谷歌应用程序制造商中使用@expr 数据进行绑定转换器?
- vb.net - 如何将对象传递给默认表单实例
- java - 来自 ExpandableListView 的子元素中的 setOnClickListener
- r - 根据用户输入日期添加新的计算列