Managing numerical data in a CSV file using JavaScript and Google Visualization Table

A JavaScript snippet provided below will load a CSV file named numericalData.csv, which contains headers in the first row and numerical values starting from the second row. The data is then displayed using a Google Visualization Table.

I am looking to convert these numerical values into either float or integer types because currently they are being treated as strings. This causes issues with sorting functionality when displaying the data (refer to the screenshot below).

   
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);

function drawTable() {            
    var csvData = loadFile("numericalData.csv", ",");
    var csvParsedData = CSVToArray(csvData);

    var data = google.visualization.arrayToDataTable(csvParsedData);

    var table = new google.visualization.Table(document.getElementById('table_div'));
    
    table.draw(data, {allowHtml: true, showRowNumber: true});
}

Answer №1

If the array csvParsedData contains strings instead of numbers, this is what you might expect to see. To resolve this issue, ensure that your CSV does not have quoted numbers. If they are not quoted and the CSVtoArray function is not parsing numbers correctly, you can iterate through your data using either parseInt or parseFloat on each value in the csvParsedData array. Below is a simplified example:

// parse all values in csvParsedData as int's
for (var i = 0; i < csvParsedData.length; i++) {
    for (var j = 0; j < csvParsedData[i].length; j++) {
        csvParsedData[i][j] = parseInt(csvParsedData[i][j]);
    }
}

[edit: updated code for handling different data types]

Here is some code that will parse data types appropriately:

// columns is an array of data types corresponding to the data types of each column in the CSV array
var columns = ['string', 'int', 'float', 'int', 'int', 'float'];
// parse all values in csvParsedData as the appropriate data type
for (var i = 0; i < csvParsedData.length; i++) {
    for (var j = 0; j < csvParsedData[i].length; j++) {
        switch columns[j] {
            case 'int':
                csvParsedData[i][j] = parseInt(csvParsedData[i][j]);
                break;
            case 'float':
                csvParsedData[i][j] = parseFloat(csvParsedData[i][j]);
                break;
            case 'string':
                break;
            default:
                // should never fire
        }
    }
}

Add other data types as needed.

Answer №2

My array is currently N rows by 5 columns with the asgallant fix already in place. I now have a requirement to include a 6th column containing only strings below it.

The structure should resemble:

Value1 | Value2 | Value3 | Value4 | Value5 | String  |
1.234      3.5     4.2      2.1      2.2      Banana  

However, my current code shows:

 Value1 | Value2 | Value3 | Value4 | Value5 |
  1.234    3.5     4.2      2.1      2.2 

Here's the existing code snippet:

 var csvParsedData = CSVToArray(csvData);
// convert all values in csvParsedData to integers
for (var i = 0; i < csvParsedData.length; i++) {
    for (var j = 0; j < csvParsedData[i].length; j++) {
        csvParsedData[i][j] = parseFloat(csvParsedData[i][j]);
    }
}

//data = google.visualization.arrayToDataTable(csvParsedData);
var data = new google.visualization.DataTable();
data.addColumn('number','Value1');
data.addColumn('number','Value2');
data.addColumn('number','Value3');
data.addColumn('number','Value4');
data.addColumn('number','Value5');
for (var j = 0; j < csvParsedData.length-1; j++){
    data.addRows([csvParsedData[j]]);
}

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

Guide to inserting text into an html element upon clicking an ASP:Button

In my code, there is a DIV that holds some text. Accompanying the text is an asp:Button. When this button is clicked, I aim to access and save this particular text. Nonetheless, it seems that once the button is clicked, the content of the DIV resets - lik ...

Nextjs introduces an innovative "OnThisDay" functionality, leveraging getServerSideProps and Date.now() to provide real-time information

I am currently working on adding an "OnThisDay" feature in my Nextjs project, inspired by Wikipedia's style of displaying events that happened on a specific date. To achieve this, I have implemented a function structured like the following code snippe ...

Issue: The npm module 'moment' cannot be located

My Meteor app works flawlessly on localhost, but when deployed to a remote heroku server, I encounter these errors. (I am following this) Any suggestions on how to resolve this issue? 2016-09-09T13:26:02.533532+00:00 heroku[web.1]: Starting process with ...

Tips for saving an image link when displaying an image in VueJS using the 'require' method

I am currently working on a project that involves displaying Pizza items with their respective images. Each Pizza object is stored in the database along with an imgUrl field. Strangely, the images are not showing up on the page, although I can see the alt ...

"Adding an Image to Another Image in HTML or JavaScript: A Step-by-Step

Hello there! I'm currently working on creating a status bar where I can add an image after another image. Let me explain my idea clearly. So, I have two images in GIF format: one is white and 10x10px, and the other one is black and also 10x10px. On ...

Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilit ...

Transmitting Several Pictures at Once Through WhatsApp-WebJS

I have encountered a challenge while attempting to send multiple images in a single WhatsApp message using the WhatsApp-WebJS library. Despite receiving a "success" confirmation without any errors, the images and message fail to appear on WhatsAp ...

Using directive to access service values directly

I am in need of utilizing a directive to fetch and display data using ng-repeat from a service. The anticipated result will be <ul>Days <li>Monday</li> <li>Tuesday</li> ... <ul> <ul>Month <li>January</li ...

What is the most secure approach for defining the file path of an HTML file within an express.js application?

In my directory setup, I have the index.js file located at: path/to/home-page/src/routes This is also where you can find the __dirname. The html file resides at: path/to/home-page/public/bootstrap/Homepage/page.html To serve the html document by relati ...

Engaging with Electron through an HTML file

Forgive my lack of experience, but I'm diving into the world of Electron and feeling a bit overwhelmed. Here's a snapshot of what I've got so far in my project: package.json: ... "main": "main.js", "scripts": { "start": "electron ." } . ...

rectangle/positionOffset/position().top/any type of element returning a position value of 0 within the container

While the height/position of the container is accurately displayed, attempting to retrieve the top position (or any position) of containing elements yields a return value of 0. Additionally, using .getBoundingClientRect() results in all values (top, left, ...

Would it be a security risk to share the Stripe charge ID and connected account ID with clients on the frontend?

I am currently making an ajax call to my backend and I am unsure whether it is secure to reveal the charge id and the connected account id on the client side. Just to clarify, there are no secret keys or sensitive information stored in the browser. Your ...

There appears to be an issue with Google Analytics not generating __utm.gif requests, yet no error messages are

I'm encountering an issue with implementing Google Analytics. Despite extensive research, I haven't been able to find a resolution. My objective is to include the user's email address as a custom variable in Google Analytics. I have integra ...

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

The not-found.js file in Next.js is displaying an empty page rather than showing a 404 error message

My current project involves using Next.js v13.4.19 with the app router mode. However, I seem to be facing an issue with the not-found.js page located in the app folder. Whenever a non-existing route is accessed, it does not render a 404 page as expected. ...

What is the best way to transfer a JavaScript variable through a query string from one HTML page to another?

Is there a way to pass a JavaScript variable called username from one HTML page, example1.html, to another HTML page, example2.html, using query strings? <script type="text/javascript" > $(document).ready(function() { $('#SubmitForm ...

Ajax sending numerous requests to the API

Recently, I began my journey of learning Javascript and decided to interact with my Django API through Ajax requests. To achieve this, I created a search bar that triggers the API call after a one-second delay following a keyup action. input.addEventListe ...

Having difficulty pinpointing and deleting an added element using jQuery or JavaScript

My current task involves: Fetching input from a form field and adding the data to a div called option-badges Each badge in the div has a X button for removing the item if necessary The issue at hand: I am facing difficulty in removing the newly appended ...

Tips for integrating Chart.js into my AngularJS application?

I am a beginner with AngularJS and I'm currently developing an application on Ubuntu. While trying to add Chart.js using npm install chart.js, an error is being displayed as follows. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Ember.js encountering an "Access-Control-Allow-Origin" error with Ajax

Seeking opinions on how to resolve the Access-Control-Allow-Origin issue in this simple Ajax code snippet. Attempts to define the Ember "Access-Control-Allow-Origin": "* " have been unsuccessful. Has anyone with a similar problem found a solution? The URL ...