Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to separate the data row by row, I'm now seeking guidance on how to achieve this same separation based on columns.

Thank you for your help in advance!

Answer №1

CSV can be represented as a two-dimensional array structure. This structure can be manipulated using nested for loops.

For instance:

for(var i = 0; i < columns.length; i++){
   for(var j = 0; j < rows.length; j++){
      matrix[i][j]
   }
}

Answer №2

While parsing CSV files may seem straightforward at first glance, it can quickly become complex depending on the source of your CSV data (whether it's user-generated, standardized from an API, etc.):

  • Dealing with headers
  • Varying numbers of headers and data columns
  • Different delimiters (e.g., Germans using ; instead of ,)
  • Number formatting differences (e.g., Germans using , as decimal separators)
  • Quoted data that may contain delimiters
  • Whitespace handling
  • Different line endings
  • ...

That is why there are numerous CSV parsers available on npm (https://www.npmjs.com/search?q=csv). Some focus on speed like https://www.npmjs.com/package/fast-csv, while others prioritize convenience such as https://www.npmjs.com/package/papaparse.

Most of these parsers return row by row to accommodate processing streams that pass data line by line rather than column by column.

Here is a code snippet to organize your data column-wise:

const input = `header_1,header_2
value 1,value 2
value 3,value 4`

// Separate rows based on known line ending \n
const rows = input.split('\n');

// Extract the header row
const header = rows.shift();

// Determine number of columns by splitting the header using , delimiter
const numberOfColumns = header.split(',').length

// Initialize 2D-array with fixed size
const columnData = [...Array(numberOfColumns)].map(item => new Array());

for(var i=0; i<rows.length; i++) {
  var row = rows[i];
  var rowData = row.split(',');

  // Assuming equal number of columns in header and data rows
  for(var j=0; j<numberOfColumns; j++) {
    columnData[j].push(rowData[j]);
  }
}

console.log("columnData = " + JSON.stringify(columnData, null, 4));

Output will be:

columnData = [
    [
        "value 1",
        "value 3"
    ],
    [
        "value 2",
        "value 4"
    ]
]

Note: This example does not cover tasks such as removing whitespace or converting numerical values.

For easier handling, you can utilize papaparse to parse data row by row and then apply a nested for loop to arrange the data into columns:

const Papa = require('papaparse');

// Example data with ; delimiter and empty lines
const input = `header_1;header_2
1;"2"

3;4`;

// Papaparse options configuration
const parseOptions = {
    quoteChar: '"',
    delimiter: ';',
    skipEmptyLines: true,
    dynamicTyping: true,
}

const parseResult = Papa.parse(input, parseOptions);
const parsedData = parseResult.data;

// Extract the header row
const header = parsedData.shift();

const numberOfColumns = header.length;

// Initialize 2D array with fixed size
const columnData = [...Array(numberOfColumns)].map(item => new Array());

for(var i=0; i<parsedData.length; i++) {
  var rowData = parsedData[i];

  for(var j=0; j<numberOfColumns; j++) {
    columnData[j].push(rowData[j]);
  }
}

console.log("columnData = " + JSON.stringify(columnData, null, 4));

Output will be:

columnData = [
    [
        1,
        3
    ],
    [
        2,
        4
    ]
]

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

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

The issue of batch-wise data clustering on Google Maps when zooming in or out

//The code snippet provided below initializes a map with specified settings and clusters markers based on the data sent in patches of 10000.// var mapDiv = document.getElementById('newmap'); map = new google.maps.Map(mapDiv, { center ...

Comparing Angular 2 Components and AngularJS Directives: What Sets

Are there any parallels or distinctions between an angular2 component and an AngularJS directive? It seems that these two share similar functionalities in the angular2 component and AngularJS directive. Additionally, angular2 also incorporates a directive ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

Is it possible to simultaneously send a JSON object and render a template using NodeJS and AngularJS?

I'm currently facing issues with my API setup using NodeJS, ExpressJS Routing, and AngularJS. My goal is to render a template (ejs) while also sending a JSON object simultaneously. In the index.js file within my routes folder, I have the following s ...

What is the best way to manage communication with a database in a Node.js application?

I have a specific structure in my Express app: There is a db helper that I use to interact with my MariaDB database Here is the code snippet: var MariaSQL = require('mariasql'); var db = new MariaSQL(); var queries = { getUserByID : &a ...

What is the best way to arrange the keys within a nested object in JavaScript?

Question: { "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } } In order to sign this request using the Hmac512 algorithm, I must first stringify the object. I am concerned that if the key order is not preserved, the generated signature on the ...

Error 404 encountered while attempting to access dist/js/login in Node.JS bootstrap

I currently have a web application running on my local machine. Within an HTML file, I am referencing a script src as /node_modules/bootstrap/dist/js/bootstrap.js. I have configured a route in my Routes.js file to handle this request and serve the appropri ...

How can you establish a default value on a paper select in Polymer?

I have a paper-select element that I want to customize with a default value when the page loads or after a specific event occurs. <dom-module id="custom-paper-select"> <template> <paper-select id="select-input-1" multiple ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

Error: anticipated expression, received keyword 'if'

I'm facing an issue that I could really use some assistance with. I am trying to hide the "changeOrderUp" button when it's in the first row, and similarly, I want to hide the "changeOrderDown" button when it's in the last row. However, FireB ...

Controller experiencing peculiar AJAX response in CodeIgniter

I recently embarked on a Codeigniter project and now I'm faced with the task of making an AJAX call to a specific controller. Here is the scenario: - I have two dropdown menus: one for selecting counties and the other should populate with cities with ...

What is the best way to instruct Ajax to choose the specific item clicked within a list?

I am currently working on creating a list of people on vacation and I want to calculate their return date when the "Return Date" link is clicked. I have been able to achieve this, however, whenever I click any of the buttons in the list, it always passes t ...

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

Is it possible to include a JavaScript script in a Laravel Blade file?

I have an Auth module from nwidart/laravel-Module. I am trying to include a script file in the Modules\Auth\Resources\views\layouts\app.blade.php file, like this: <body> ...... ... <!-- Scripts --> <script s ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

Problems arise with identification of asynchronous functions

My async functions have been used successfully in various projects, but when incorporating them into a new project, they suddenly stopped working. One of the functions causing trouble is: const ddbGet = async (params) => { try { const data ...

When trying to find a substring within a string in JavaScript, the "else if" statement may not be triggered

I'm currently working on creating a Hangman game using HTML and JS. Most of the code is functioning properly, but I've hit a roadblock. For some reason, one part of my if else statement isn't working correctly. Here's the line of code: ...

Encasing a series of AJAX calls in a function: Implementing JavaScript and JQuery

I am facing an issue with a chain of two AJAX requests within a forEach() loop, where the second request relies on the response of the first. I have tried to wrap this code block in a function for reusability, but it seems to stop working. As a beginner in ...