From a single array to four separate arrays

I currently have an array structured as follows:

[{
    "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"
}]

What I aim to achieve is the creation of four separate arrays:

array coins:
[{ "AION", "BTC" }]
(additional coins can be included based on the existing array) > AION, BTC, ETH, ZIL, ARK, etc....

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

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

array timestamp:
[{ "2021-01-26 00:48","2021-01-26 01:08" }]
(additional timestamps based on the initial array)

This information is crucial for populating the chartsData array for am4charts.LineSeries.

Is there anyone who can assist me with this task? Alternatively, are there any better approaches available?

Answer №1

When faced with a problem that involves iterating over elements of an array and grouping them based on specific rules, it's a good opportunity to utilize Array.reduce, although there are other methods that can achieve the same result.

One approach to solving this type of problem is by creating a function like the following:

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
}

Instead of grouping exactly as requested, this function organizes the profit of each entry along with its timestamp. The output would look something like this:

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

Answer №2

const dataArray=[{
    "coin": "ETH",
    "profit": "2.30",
    "timestamp": "2021-02-08 09:48:19"
},
{
    "coin": "LTC",
    "profit": "10.50",
    "timestamp": "2021-02-08 07:08:32"
},
{
    "coin": "ETH",
    "profit": "3.40",
    "timestamp": "2021-02-08 11:12:56"
},
{
    "coin": "LTC",
    "profit": "12.25",
    "timestamp": "2021-02-08 10:38:21"
}]
let timestampData=[...new Set(dataArray.map(entry=> entry['timestamp']))]
let coinData=[...new Set(dataArray.map(entry=> entry['coin']))]
let ethProfit=[],ltcProfit=[];
dataArray.map(entry=>{
  if(entry.coin==='LTC')
    ethProfit.push(entry.profit)
   else
    ltcProfit.push(entry.profit)
})
console.log(coinData,ethProfit,ltcProfit,timestampData)

Answer №3

To efficiently group and construct the desired output, you can leverage the Array.prototype.reduce function.

const data = [{    "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"}],
      result = data.reduce((acc, {coin, profit, timestamp}) => {
        acc.coins.push(coin);
        acc.timestamps.push(timestamp);
        (acc.profits[coin] || (acc.profits[coin] = [])).push(profit);

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What sets apart jQuery's `click`, `bind`, `live`, `delegate`, `trigger`, and `on` functions, and how can they be utilized differently in coding

I have gone through the documentation for each function provided on the official jQuery website, but I couldn't find any comparison listings for the following functions: $().click(fn) $().bind('click',fn) $().live('click',fn) $().d ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

The table is failing to update its data when I attempt to refresh it using the custom button on the page

I need to incorporate a refresh button using an angular material icon on my webpage that triggers an HTTP call to retrieve the latest data and update the view. I have implemented a $watch function to monitor any updates. Below is the corresponding JavaScri ...

Integrate Arduino's capabilities with Johnny-Five within an HTML JavaScript document

As a beginner in the world of JavaScript, I set out to embark on a project involving turning on a connected LED on an Arduino board by simply pressing a button on an HTML page. After doing some research, I came across a JavaScript library called "johnny- ...

Guide on Incorporating Coffeescript into the Node.js Blueprint Framework

Have you checked out Skeleton (https://github.com/dstroot/skeleton) yet? It appears to be a robust framework for node.js, offering all the middleware you need. However, it seems to lack support for coffee script. How can we incorporate it into our project? ...

Stop the loop in cypress

We have a certain situation as outlined below loop through all name elements on the webpage if(name.text() matches expName) { name.click() break out of the loop } else { createName() } How can I achieve this in Cypress? Using return false doesn't se ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

What could be preventing my component from importing properly in App.vue?

I am attempting to display a pulse loader while the page is loading. However, I encountered two errors in the code below. App.vue <template> <div id="app"> <div id="nav"> <router-link to='/'><div v-if="$ro ...

I keep encountering the issue where nothing seems to be accessible

I encountered an error while working on a project using React and Typescript. The error message reads: "export 'useTableProps' (reexported as 'useTableProps') was not found in './useTable' (possible exports: useTable)". It ...

Determine the status of all jqXHR requests within an array to confirm completion

My goal is to execute a block of code once all the jqXHR elements in an array have completed, whether they have succeeded or failed. For the full code, you can check it out here: http://jsfiddle.net/Lkjcrdtz/4/ Essentially, I am anticipating the use of t ...

Error: The code is trying to access the property 'string' of an undefined variable. To fix this issue, make sure to

I encountered an issue after installing the https://github.com/yuanyan/boron library. The error message I received is: TypeError: Cannot read property 'string' of undefined Error details: push../node_modules/boron/modalFactory.js.module.expor ...

How to identify and assign labels to elements in a numpy group

I have a solid grasp on how to assign labels to elements in one input array as shown below: arr_value = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 2, 1, 1, 1, 1]) arr_res_1 = np.array([0, 1, 2, 3, 3, 4, 5, 6, 7, 7, 8, 9, 9, 9, 9]) # treat zeros in arr_value ...

Sorting swiftly using pointers

For my homework assignment, I am tasked with coding a quick sort algorithm in C. The given prototype is as follows: static inline int* choose_pivot(int *left, int *right) { /* FIX ME */ } /* * partition(left, right, pivot): push value less than *piv ...

You can disregard the first option in a multiple select box using jQuery

Imagine having multiple select boxes with the same options that are mutually exclusive. For instance, if Select Box A and Select Box B both have Option 1, Option 2, and Option 3, selecting Option 1 for Select Box A should make it unavailable in Select Box ...

What is the best way to connect a text box to a nested object in the state of a React component?

Solving a React Debugging Dilemma In my current project, I'm developing an office add-in using a React-based starter kit and TypeScript. Unfortunately, debugging has been a challenge as I am unable to access detailed error messages from React in my s ...

How do I make the YouTube Grid Gallery player show up in a pop-up window?

I have been experimenting with the following code: <head> <script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script> <script type="text/javascript"> function loadVideo(playerUrl, ...

Troubleshooting problems with image display following jQuery animation

Check out this awesome page I found: where you can see a neat list of blog posts displayed in rows of 4. I've added a cool jQuery animation to the 'cards' so that they fade in one by one: jQuery('.fade-in-post-container .elementor-po ...

Finding the precise Time zone with date-fns: A comprehensive guide

I've implemented a date pipe using the date-fns library for formatting dates. Here is the code: date.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { format } from 'date-fns'; @Pipe({ name: 'formatDate ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. https://i.sstatic.net/PnIDa.png After inspecting each number, it was ...

Organizing your code with precision

I'm struggling with a project due to the poorly formatted code, making it almost impossible to read. Despite my attempts with various plugins and tools in VIM, Netbeans, Sublime Text 2, and Eclipse, the situation only seems to worsen. If anyone has ...