一排到四排

问题描述

我有一个这样的数组:

[{
    "coin": "AION","profit": "3.10","timestamp": "2021-01-26 00:48:01"
},{
    "coin": "BTC","profit": "77.00","timestamp": "2021-01-26 00:08:04"
},{
    "coin": "AION","profit": "4.00","timestamp": "2021-01-26 01:08:01"
},"profit": "78.10","timestamp": "2021-01-26 01:08:04"
}]

但我实际需要的是四个(四个是可变的)数组:

array coins:
[{ "AION","BTC" }]
(variable with extra coins,depending on the first array i already have) > AION,BTC,ETH,ZIL,ARK,etc....

array profit[AION]:
[{ "3.10","4.00" }]

array profit[BTC]:
[{ "77.00","78.10" }]
(Variable extra coins/profits) [ETH,etc...]

array timestamp:
[{ "2021-01-26 00:48","2021-01-26 01:08" }]
(Variable extra timestamps depending on first array i already have)

我需要这个来填充 am4charts.Lineseries 的 chartsData 数组。

有人可以帮我吗?或者有没有更好的选择?

解决方法

这种问题是您遍历数组的元素并根据某些规则对某些内容进行分组。

这是 Array.reduce 的一个很好的用例(虽然你可以用其他方法做同样的事情)

我会做类似这样的功能:

function indexByCoins(coinsArray) {
    const coinsProfitByCoin = coinsArray.reduce((accumulator,coinInfo) => {
        const { coin,profit,timestamp } = coinInfo

        if (!accumulator[coin]) {
            accumulator[coin] = []
        }

        accumulator[coin].push({ profit,timestamp })
        return accumulator
    },{})

    return coinsProfitByCoin
}

它没有按照您的要求完全,而是将每个条目的利润与其时间戳分组。所以你会得到:

{
  AION: [
    { profit: '3.10',timestamp: '2021-01-26 00:48:01' },{ profit: '4.00',timestamp: '2021-01-26 01:08:01' }
  ],BTC: [
    { profit: '77.00',timestamp: '2021-01-26 00:08:04' },{ profit: '78.10',timestamp: '2021-01-26 01:08:04' }
  ]
}
,
let arr=[{
    "coin": "AION","profit": "3.10","timestamp": "2021-01-26 00:48:01"
},{
    "coin": "BTC","profit": "77.00","timestamp": "2021-01-26 00:08:04"
},{
    "coin": "AION","profit": "4.00","timestamp": "2021-01-26 01:08:01"
},"profit": "78.10","timestamp": "2021-01-26 01:08:04"
}]
let timestampArr=[...new Set(arr.map(item=> item['timestamp']))]
let coinArray=[...new Set(arr.map(item=> item['coin']))]
let AionProfilt=[],btcProfit=[];
arr.map(item=>{
  if(item.coin==='BTC')
    AionProfilt.push(item.profit)
   else
    btcProfit.push(item.profit)
})
console.log(coinArray,AionProfilt,btcProfit,timestampArr)
,

您可以使用函数 Array.prototype.reduce 对所需的输出进行分组和构建。

const array = [{    "coin": "AION","timestamp": "2021-01-26 00:48:01"},{    "coin": "BTC","timestamp": "2021-01-26 00:08:04"},{    "coin": "AION","timestamp": "2021-01-26 01:08:01"},"timestamp": "2021-01-26 01:08:04"}],result = array.reduce((a,{coin,timestamp}) => {
        a.coins.push(coin);
        a.timestamps.push(timestamp);
        (a.profits[coin] || (a.profits[coin] = [])).push(profit);

        return a;
      },{coins: [],profits: {},timestamps: []});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }