Converting JavaScript Array into a Two-Dimensional Array

I'm currently working on a dashboard project to display data from multiple stats sources. I am utilizing Django along with Google Charts for creating visually appealing graphs. While the process has been smooth so far, I have hit a roadblock in one specific scenario.

The model class looks like this-

class Registration(models.Model):
    event_type = models.CharField(max_length=80)
    date_time = models.DateField()
    count = models.IntegerField()

The query in question is-

Registration.objects.filter(event_type__in=['VHRAssmntCompleted', 
    'VNAAssmntCompleted', 
    'NonsmokersDeclrtn',
    'MWBAssmntCompleted',
    'VHCAssmntCompleted',
    'SV Document Uploads',
    'PapSmear',
    'Mammogram',], 
    date_time__range=(d3,d1)).order_by('date_time')

The current format of the retrieved data is as shown below:

[["VHR", "2019-02-1", 23],
["VNA", "2019-02-1", 34],
["PAP", "2019-02-1", 50],
["VHR", "2019-02-2", 92],
["VNA", "2019-02-2", 13],
["PAP", "2019-02-2", 65],
["VHR", "2019-02-3", 192],
["VNA", "2019-02-3", 43],
["PAP", "2019-02-3", 11]]

In order to create a Combo Chart, I need the data to be structured as follows (similar to a Python dataframe):

[["date", "VHR", "VNA", "PAP" ],
["2019-02-1", 23,34,50],
["2019-02-2", 92,13,65],
["2019-02-3", 192,43,11]]

I am struggling to figure out a method to achieve this goal, whether it's through formatting within the Django ORM query itself or converting using JavaScript.

If anyone could provide guidance on the best approach to take, it would be greatly appreciated.

Answer №1

To organize the data by date and column position, you can create an object to map the values accordingly.

var data = [["ABC", "2020-05-15", 10], ["DEF", "2020-05-15", 20], ["GHI", "2020-05-15", 30], ["ABC", "2020-05-16", 15], ["DEF", "2020-05-16", 25], ["GHI", "2020-05-16", 35], ["ABC", "2020-05-17", 5], ["DEF", "2020-05-17", 12], ["GHI", "2020-05-17", 28]],
    columns = { ABC: 1, DEF: 2, GHI: 3 },
    results = data.reduce((result, [key, date, value]) => {
        var row = result.find(([d]) => d === date);
        if (!row) {
            result.push(row = [date, 0, 0, 0]);
        }
        row[columns[key]] = value;
        return result;    
    }, [["date", "ABC", "DEF", "GHI"]]);

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

Answer №2

You have the option to group them based on their dates, and then iteratively go through the grouped outcome using Object.entries to convert it into [date, "VHR", "VNA", "PAP"]

const dataset = [
  ["VHR", "2020-05-1", 56],
  ["VNA", "2020-05-1", 28],
  ["PAP", "2020-05-1", 37],
  ["VHR", "2020-05-2", 14],
  ["VNA", "2020-05-2", 59],
  ["PAP", "2020-05-2", 42],
  ["VHR", "2020-05-3", 63],
  ["VNA", "2020-05-3", 85],
  ["PAP", "2020-05-3", 72]
];

const groupedData = dataset.reduce((aggregate, [key, date, value]) => {
  aggregate[date] = {
    ...aggregate[date],
    [key]: value
  };
  return aggregate;
}, {});

const finalResult = ["Date", "VHR", "VNA", "PAP"].concat(
  Object.entries(groupedData).map(([date, details]) => [date, ...Object.values(details)])
);

console.log(finalResult);

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

Error loading jakefile: Unable to load file

After attempting to use Jake, I encountered a strange issue where Jake was unable to load the Jakefile. Any suggestions on how to resolve this? Directory Structure: jake_test >> jake.sh jake_test >> jakefile.js jake.sh file node_modules/.b ...

arrange elements in php array using any specific key

Within my PHP code, I have an array structured like this: $myarray[$index]['height'] $myarray[$index]['weight'] $myarray[$index]['age'] I am looking for the most effective function to sort this array by either 'height&a ...

Is it possible to store an HTML element tag in a variable?

I've been learning JavaScript on w3schools and freecodecamp, but I stumbled upon something in w3schools that has me puzzled. Can someone please explain why this particular code snippet works? The variable "text" is declared as containing the string " ...

Symfony2 encountering difficulties in locating file after deployment

Upon launching my project on the live server, I encountered the following error: An error occurred during template compilation ("Could not locate file "@JDareClankBundle/Resources/public/js/".") in "JDareClankBundle::client.html.twig". I have tried clear ...

The tab does not appear after it is added

Currently, I am developing a dashboard using ReactJS with Redux. One of the key features is the ability to create tabs. When a tab is created and saved through a POST request to the API for database storage, it should also be displayed in the header immedi ...

Dropdown Box Linking and Input Field Integration in HTML

I have a scenario where students need to pay monthly fees for their classes. My objective is as follows: 1. Dropdown #1: Student Names 2. Dropdown #2: Month Names 3. Textbox: Fees amount for the selected month The code I am using: $(document).ready(fu ...

Enhance user experience with CSS animations and automatic page reloading on the previous page for both iOS and Android

I need help finding a solution for a transition effect I am implementing in my project. The effect I want to achieve is as follows: Page fades in with an opacity that transitions from 0 to 1 using @keyframes When any link is clicked, the page opacity goe ...

Issues with Functionality After Transition to Bootstrap

I have successfully implemented a working form, but it lacks style and looks unappealing: {{ form.non_field_errors }} <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /& ...

Pushing items to an array is causing the loss of previously added data

Currently, I am working on developing a prototype of a Restaurants application using Angular 8. In this project, I have implemented @Input() to transfer individual restaurant data as an object from the parent component to the RestaurantCardComponent for pr ...

Is it possible for me to include a variable with the xmlhttp response text?

There is a function defined as follows: function call_view_details(viewid) { view_details(viewid); setInterval(function(){view_details(viewid)},5000); } which I invoke when the page loads. Its main purpose is to set intervals for view_details(). ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Make sure that the second input value is smaller than or equal to the first value when the key is

I am working with three input values - one for the payment, a second for the advance payment, and a third for the remaining balance from the actual payment to the advance payment. If the advance payment is greater than the actual payment, it should not be ...

What is the best way to choose a file and transform it into a string using React?

In the backend of my application (using express and mongodb), there is a field within the post model called picture with a string data type. In the frontend (built with React), I am looking to allow users to select a file, convert it to a string, and sen ...

Creating a fluid side navigation bar in reactjs

Can someone please help me with the following code issue? I am encountering an error related to the script tag when running it in ReactJS, although it works fine in a simple HTML file. Upon starting npm, an error is displayed pointing to line number which ...

Show the form when the button is clicked

I want to create an application that allows users to click on a button in the top right corner (check image) to hide one div (topics) and show another div (a form for adding a new topic). Here is what it looks like: https://i.stack.imgur.com/YeRTw.png ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

Implement jQuery plugin selectively in AngularJS on particular pages

Struggling with Angular JS and trying to integrate the Liquid Slider jQuery Plugin. While I find Angular JS intriguing, I still have a lot to learn before fully utilizing it. Any assistance would be greatly appreciated. The objective: Implementing the Liq ...

Angular Pagination: An issue arises when deleting records from the first page, as the following page's records are not automatically refilling the first page

I have implemented angular pagination to display records. Each record has a button labeled 'Assign to me'. Clicking on this button removes the selected record from the list. However, I am facing an issue where I display 10 records per page and if ...

Learn how to use a variable as the url_name in Django's url tag!

Within my Django view, I have declared a variable called target: target = "name_of_next_view_to_call" return render(request, template, locals() ) I attempted to use this target variable in my template by doing the following: <form action="{% url &ap ...

Running Discord.js RPC on a GTA or Minecraft server

Can a Rich Presence be hosted on a Minecraft server or an Alt:v GTA server so that all players who join have it in their status? ...