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

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Creating a Timeless Banner with the Magic of `background:url()`

I have a banner placed within a div tag that displays my banner image. I am trying to create a fading effect when transitioning to the next image, but I am struggling to achieve this. I attempted to use jQuery fadeIn(), however, it did not work as expected ...

Transform every key and value into an array

How can I separate each key and value into individual arrays? Here is the current data: var inputArray = { "3/10/2017": 52, "3/11/2017": 58, "3/12/2017": 70, "3/13/2017": 76 } The desired output should be: var outputArray = [ ["3/10/2017", 52 ...

Unable to establish a new pathway in the index.js file of a Node.js and Express website running on Heroku

I recently made some changes to my index.js file: const express = require('express'); const path = require('path'); const generatePassword = require('password-generator'); const fetch = require('node-fetch'); const ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

Using the history.push() method from the Action Creator will update the URL without actually redirecting to a new page

I have a login page component that I've set up to redirect to another page after a successful login. However, even though the URL changes correctly, the page remains on the Login page. First, let me show you how I import the history module to be used ...

Express callback delaying with setTimeout

I'm working on a route that involves setting a data attribute called "active" to true initially, but then switching it to false after an hour. I'm curious if it's considered bad practice or feasible to use a setTimeout function within the ex ...

Make the textarea larger and bring it to the forefront when it is selected

I would like to make a textarea expand (increase its height) when it is in focus. The expanded textarea should not push the content down, but rather be displayed above other content. Currently, this is the code I am using (check out the example here): $( ...

Create a setup page upon initial login using express.js

Currently, I am implementing Passport.js for user authentication on my express.js application. I aim to display a setup page upon the initial login of the user. Is it possible to achieve this using Passport? ...

Error encountered during file download with AXIOS: TypeError - 'validateStatus' in blob cannot be searched using 'in' operator

I recently encountered an issue with a Vue app when attempting to download a CSV file using Axios, and I am unsure of how to resolve it. downloadFile: function(res = "") { axios .get('/api/file/' + res, 'blob') ...

Using asynchronous file uploading with jQuery and ASP.NET for a seamless user experience

I recently came across an article on Async file upload in ASP.NET which you can find here. Although the process was working fine up until the .ashx file call, I encountered an issue where "context.Request.Files.Count" showed 0. Any help or suggestions wo ...

What is the best way to create a sliding animation on a div that makes it disappear?

While I may not be an expert in animations, I have a question about sliding up the "gl_banner" div after a short delay and having the content below it move back to its original position. What CSS properties should I use for this animation? Should I use css ...

Collapse the sidebar using React when clicked

Just beginning to learn about React and I'm trying to figure out how to toggle the open/closed state of a react-pro-sidebar component using a click event: export default function MaterialLayout(props) { const { children } = props; const classes = us ...

Create static HTML files using an Express server

Recently, I developed a nodejs web project using express-js and ejs. However, upon further reflection, it occurred to me that hosting it as static html files on Netlify might be more cost-effective than running it as a nodejs app on Heroku. Since the data ...

Elements with v-for directive failing to display

I am attempting to incorporate a component using v-for. The data source infoTexts is structured as an Object where the locale code serves as the key and the corresponding message is the value. For example: { nl: 'Text in Dutch', fr: &apo ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

`CSS Content Placeholder Issue When Used Alongside JavaScript`

Let me explain a bit, I have a master page named UserProfile.master which has a content placeholder linked to UserProfileWall.aspx. Now, I am trying to incorporate some additional JavaScript and a second CSS file in the userprofilewall page. However, whene ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

Is it possible to animate the innerHTML of a div using CSS?

In my HTML file, I have these "cell" divs: <div data-spaces class="cell"></div> When clicked, the innerHTML of these divs changes dynamically from "" to "X". const gridSpaces = document.querySelectorAll("[data-spaces]"); f ...

What causes addEventListener to not return a value?

In this snippet of code: let rockClick = rockBtn.addEventListener('click', playRound.bind("rock", computerPlay(), false)); After using console.log(), the output is undefined. The purpose of rockBtn:const rockBtn = document.querySelecto ...