Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

javascript - One array to four arrays

I have one array like this:

[{
    "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"
},
{
    "coin": "BTC",
    "profit": "78.10",
    "timestamp": "2021-01-26 01:08:04"
}]

But what i actually need is four (four is variable) arrays:

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, ZIL, ARK, etc...]

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

I need this to fill chartsData array for am4charts.LineSeries.

Can someone help me please? Or is there any better option for this?

question from:https://stackoverflow.com/questions/65907973/one-array-to-four-arrays

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is the kind of problem where you're iterating over elements of an array and grouping some stuff depending on some rules.

It's a good use case for Array.reduce (although you can do the same thing with other methods)

I would do something like this function:

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
}

It doesn't do exactly as you asked, instead it groups the profit of each entry with its timestamp. So you'd get:

{
  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' }
  ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...