首页 > 解决方案 > 匹配对象数组中的对象键并返回键,具有最高音量值的值

问题描述

我有一个对象数组,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
}]

标签: javascriptarraysobjectecmascript-6

解决方案


如果该项目的值大于该键的当前项目的值,则一种方法是迭代的值tickerA并将它们映射到键:baseAssetvolumebaseAsset

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


推荐阅读