Splitting a Multidimensional Array in JavaScript into Two Separate Arrays

I received an array from an ajax call (data) that I need to split into two parts:

An alert showing the data reveals:

[[200326,150000],[200327,150000],[200328,150000],[200329,150000],[200330,160000],[200331,320000]]

I attempted to extract the dates (first element) like 200326...200331 and the prices (second element) using this code:

var dates = [];
var prices= [];
var datason = JSON.parse("[" + data + "]");
for (var i in datason) {
    dates.push(datason[i][0]);
    prices.push(datason[i][1]);
}

The alert displaying datason shows:

200326,150000,200327,150000,200328,150000,200329,150000,200330,160000,200331,320000

Next, I want to display a canvas graph:

var chartdata = {
                        labels: dates,
                        datasets: [
                            {
                                label: 'Evolution',
                                backgroundColor: '#49e2ff',
                                borderColor: '#46d5f1',
                                hoverBackgroundColor: '#CCCCCC',
                                hoverBorderColor: '#666666',
                                data: prices
                            }
                        ]
                    };

Thank you for your help!

Answer №1

Avoid the unnecessary inclusion of additional square brackets; your data already contains them.

Consider this approach instead:

var dates = [];
var prices= [];
var datason = JSON.parse(data);
for (var i in datason) {
    dates.push(datason[i][0]);
    prices.push(datason[i][1]);
}

Answer №2

Have a look at this code snippet for some assistance.

let data = [[200326,150000],[200327,150000],[200328,150000],[200329,150000],[200330,160000],[200331,320000]];

const { dates, prices } = data.reduce(
  ({ dates, prices }, current) => ({ 
    dates: [ ...dates, current[0]],
    prices: [ ...prices, current[1]]
  }), 
  { dates: [], prices: [] }
);

console.log(dates);
console.log(prices);

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

HAproxy: unique error handling for OPTIONS and POST requests with 503 errorfile

Our Web application utilizes ajax calls to a backend that operates on a different domain, requiring CORS. The backend setup includes an HAproxy 1.4.22 along with multiple Wildflys running on the OpenShift PaaS. During times when a Wildfly instance is unava ...

What is the best way to display a webpage within an iOS app using PhoneGap?

In my iOS phonegap app, I am looking to have a single view that displays a web page. Can someone guide me on how to load this specific view with a particular URL using JavaScript? Although I primarily develop native iOS applications and do not have expert ...

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

Guide to printing elements from an ArrayList in Java

I need help with randomly selecting and printing an item from an ArrayList that I created from an Array. Can someone provide guidance on how to achieve this? The code snippet below shows what I have done so far. public class Song { final String[] s ...

Arrange the array in ascending order based on a specific value

Within my array, I have various objects of different types: myArray = [ {state: "enabled", name: "zName"}, {state: "trying", name: "aName2"}, {state: "disabled", name: "aName3"}, {state: "dis ...

Is the value incorrect when using angular's ng-repeat?

Currently iterating through an array nested within an array of objects like this: <div ng-repeat="benefit in oe.oeBenefits"> <div class="oeInfo" style="clear: both;"> <div class="col-md-2 oeCol"> <img style="he ...

Encountering problem with rendering the header in the footer within a customized package built on react

I am currently working on creating a node package that consists of simple HTML elements. The package is named fmg_test_header. These are the files included in the package: header.jsx index.js package.json header.js function Header() { return "< ...

What is a reliable method for automatically refreshing a webpage despite encountering server errors?

I'm working on an HTML+JS web page that refreshes itself automatically every few seconds using http-equiv="refresh". The problem is, sometimes the server returns a 502 "bad gateway" error, preventing the HTML code from loading and causing th ...

Creating a responsive database search query using Node.js and MySQL

I am attempting to pass a dynamic value from node using the mysql npm package. I am confident there is a syntax error, but I am struggling to make the query function correctly. Below is the function that triggers the query: function checkInventory() { ...

Capable of generating an ajax URL parameter conditionally for utilization with jQuery Validate

I am having an issue with my jQuery validation script. What I am trying to achieve is this: when a user clicks the send button, the script will determine whether to execute an if or else statement based on the last portion of a string (isAdd). Subsequently ...

Uh-oh! Angular 6 has encountered an unexpected error with template parsing

I am currently working on an Angular application where I have integrated the FormsModule from '@angular/forms' in my app.module.ts. However, despite this, I keep encountering the error message No provider for ControlContainer. Error log: Uncaug ...

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

Is there a way to modify the value of a JavaScript object?

My React componentwillmount fetches data from an ExpressJS API using Axios and receives a JSON response, which is then converted to an object by Axios. [{"client_nick":"PlayTalk","connected_time_record":183710127},{"client_nick":"PlayTalk","connected_time ...

I'm curious about the meaning of "!" in pseudo-code. I understand that it represents factorial, but I'm unsure of how to properly interpret it

Can someone explain the meaning of ! in pseudo-code to me? I understand that it represents factorial, but for some reason I am having trouble translating it. For example: I came across this code snippet: if (operation!= ’B’ OR operation != ’D’ O ...

What could be causing the Angular HTTPClient to make duplicate REST calls in this scenario?

I am encountering an issue with my Angular service that consumes a Rest API. Upon inspecting the network and the backend, I noticed that the API is being called twice every time: Here is a snippet of my Service code: getAllUsers():Observable<any>{ ...

Utilizing Route Parameters in Node.js

frontend.jade doctype html html head meta(charset='utf-8') //if lt IE 9 script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js') // [if gte IE 9] <! scr ...

Guide to saving an Object to a file (JSON) within the project directory using React Native for Debuggingpurposes

Feeling a bit overwhelmed trying to tackle this issue. My goal is to save data to a JSON file in real-time while debugging my application. I have a Redux store state that I want to organize neatly in a file for easier debugging, so exporting/writing the ob ...

Different method of including the ng-click attribute on the body element

Greetings! I am currently developing a chrome extension and incorporating Angular to prevent any conflicts with other Angular pages. To avoid conflicts, I am attempting to set an ng-click on the body element. Here is the code snippet I used: var body = do ...

Display navigation bar upon touch or lift

In the mobile version of a website, there is a fixed navigation bar at the top. The positioning of this navbar is achieved using position:absolute: .navbar-fixed-top{position:absolute;right:0;left:0;z-index:1000; The goal is to make the navbar invisible ...

Change web page in JavaScript using post data

Is there a method to utilize JavaScript for navigating to a new URL while including POST parameters? I am aware that with GET requests, you can simply add a parameter string to the URL using window.location.replace(). Is there a way to achieve this with ...