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

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...

Utilizing AJAX to dynamically update a DIV element in CodeIgniter's controller

I need to continuously update a small chat between two users every minute. The functionality is working, but I am struggling with implementing an AJAX call to update the DIV that displays the messages. var interval window.onload = function(){ interval ...

What could be the reason behind the malfunctioning of my three.js lighting system?

I am struggling to identify the issue with this code snippet (http://jsfiddle.net/resistdesign/s6npL/). Despite referencing the documentation and some examples, the lights don't seem to be functioning as expected. var camera, scene, renderer, geometr ...

retrieving session variables from the server side in javascript

I have set a session variable in the backend (code-behind ascx.cs page) and now I need to access that same value in a checkbox checked event using JavaScript. Below is my JavaScript function code: $(document).ready(function () { $('#<%= gvPR ...

Organize a collection of objects into a fresh array

I am facing an issue where I have an array and I need to transform it into an array of its children elements. var data = [{ name: 'Cars', content: 'BMW', value: 2000 }, ...

Utilizing an argument in the mapStateToProps function

This component features a counter along with two buttons for incrementing and decrementing the count. class App extends Component { render() { return ( <div className="App"> <h1>{this.props.counter}</h1> <b ...

Locate records in MongoDB by leveraging the power of Mongoose

Managing two distinct databases, one for products and another for categories. The product schema is defined as follows: const productSchema = new mongoose.Schema({ name: { type: String, required: true }, description: { type: String, required: true }, ...

What is the process of using a For loop to output a string in reverse order?

I'm attempting to reverse the string "hello" using a For loop, aiming for the output of "olleh". However, I'm facing an issue where the last character in the string is not being removed after being added to the array. Consequently, only the last ...

Need help with a countdown function that seems to be stuck in a loop after 12 seconds. Any

I am facing an issue with a PHP page that contains a lot of data and functions, causing it to take around 12 seconds to load whenever I navigate to that specific page. To alert the user about the loading time, I added the following code snippet. However, ...

Utilize Vue to localize the click events of buttons on the webpage

I have a scenario where I have several buttons on a page, and when I click one to toggle its text, all of the buttons change. How can I utilize VUE to isolate functionality and make each button's @click event only affect the clicked button? In the cod ...

Determine the row index by identifying the row id and table id

I need to retrieve the Index number of a row when a hyperlink is clicked, while also passing additional data from this tag. <a href="javascript:void(0);" onclick="EditDoctorRow(' + RowCountDoctorVisit + ');"> <i class="fa fa-edit"&g ...

Display an array of objects using React within the columns of a Bootstrap grid

I am facing a challenge where I have an array of components that I need to render in separate cells. The number of elements in the array can vary, sometimes exceeding the limit of 12 cells in the Bootstrap grid system. In such cases, I need to create new r ...

I can only use innerHTML once in my React application

I am attempting to clear my container div when the user clicks the search button in order to remove all existing search results. However, I am encountering an issue where using innerHTML to clear the container div only works the first time. If a second sea ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

The cause of Interface A improperly extending Interface B errors in Typescript

Why does extending an interface by adding more properties make it non-assignable to a function accepting the base interface type? Shouldn't the overriding interface always have the properties that the function expects from the Base interface type? Th ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Is there a way to enlarge images when hovered using canvas?

I came across a fascinating example at the following link: , where the images expand when hovered over. I am aware that this can be achieved using jquery, but I have concerns about its speed and reliability. I would like to experiment with d3.js, although ...

The random quote generator or current tweet quote feature is malfunctioning

I am having trouble with a jQuery on click function that is not working to tweet the current quote. I am working on building a random quote machine and tweeting the current quote is essential. Despite successfully implementing the JSON API, I cannot seem t ...

Ways to modify font color in JavaScript "type"

Recently, I came across a fascinating technique where by simply refreshing the page, the text changes sentences. I managed to implement the code successfully, however, I am having trouble changing the color, size, and alignment of the text. <script type ...