What is the best way to divide an array into separate columns in JavaScript?

Hey there fellow JavaScript enthusiasts!

I am working with an array that I created from data extracted from a csv file. Here's a snippet of how it looks:

https://i.sstatic.net/tczVz.png

Each index in the array, for example array[0], represents the headers with a total of 87 in this instance. The subsequent arrays within the array represent the rows of data.

My goal is to extract and organize this data into columns.

The code snippet below accomplishes this task but only for the first column:

      var specialCounter = 0;
        for(var j = 1; j<vm.lines.length; j++){
            vm.columns.push(vm.lines[j][0]);

            if(specialCounter >= vm.lines[j][0].length)
                specialCounter = 0;
            else
                specialCounter++;
        }

        vm.columnData.columnData= vm.columns;

        console.log(vm.columnData);

Here's the array output generated by the code above:

https://i.sstatic.net/Khwvc.png

How can I extend this logic to work with all columns in the array?

Perhaps utilizing a structure like

vm.dataPerColumn = [{column1: [...], column2: [...], etc...]

Answer №1

Using the reduce method on the array, each sub-array is checked using the forEach method to see if a key exists. If a key does not exist, it is created on the result object (r) and the current item is pushed to that key:

var arr = [['h1', 1, 2, 3], ['h2', 4 , 5 , 6], ['h3', 7, 8, 9]];

var result = arr.reduce(function(r, a) {
  a.forEach(function(s, i) {
    var key = i === 0 ? 'headers' : 'column' + i;
    
    r[key] || (r[key] = []); // if key not found on result object, add the key with empty array as the value
    
    r[key].push(s);
  });
  
  return r;
}, {});

console.log(result);

Answer №2

After reviewing the description and examining the image, it appears that the headers are located within array[0]

const vm = {};
vm.lines = [["$", "house", "car"],[5, 10, 15],[25,35,45]]; 

const headers = vm.lines[0];
const data = vm.lines.slice(1);

const columns = data.reduce((newColumns, row) => {
    for(let i=0;i<row.length;i++){
        if(newColumns.length-1 < i){ //first column;
            newColumns.push([]);
        }
        newColumns[i].push(row[i]);
    }
    return newColumns;
}, []);

const columnsWithHeaders = headers.map((header, index) => ({[header]:columns[index]}));

console.log(columnsWithHeaders);

You asked for column1, column2, etc., but it may be more logical to pair the header name with the corresponding column, making it easier to reference directly.

What has been done is the separation of headers and data, eliminating the need to worry about the first line,

The next step involves converting rows into columns, allowing for a direct association of each column array with its respective header.

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

When you hover over HTML tables, they dynamically rearrange or shift positions

Issue: I am encountering a problem with multiple tables where, upon hovering over a row, the tables are floating rather than remaining fixed in place. Additionally, when hovering over rows in the first or second table, the other tables start rendering unex ...

Greasemonkey script causing interference with other website scripts

Although my Greasemonkey script is functioning exactly as I want it to, it seems to be blocking the website's own JavaScripts. As a result, these scripts are no longer working. I have been using the incredibly useful waitForKeyElements() function to ...

Is there a method to introduce a line break for each piece of data that is shown?

I am currently working with an array and have successfully displayed it on the screen. My inquiry is whether it is feasible to insert a line break for each of the data points it presents. { name: "cartItems", label: "Product Name ...

The module 'pouchdb' appears to be missing, functioning correctly on Mac but encountering issues on Windows

I have taken over a project built with Ionic that was originally developed on a Mac by my colleague. I am now trying to run the project on my clean Windows 10 PC with Ionic, Cordova, and Python installed. However, I am encountering an error that my colleag ...

Unlocking the Secret: How to Bind a Global Touch Event Handler in Angular 4 to Prevent iOS Safari Page Drag

The issue at hand is that within my Angular 4 application, there is a D3.js chart that relies on user touch input for dragging a needle to a specific value. The drag functionality is triggered by 'touchstart', while the registration of the final ...

A guide on ensuring all necessary keys are present in a JSON document using Node.js

I have been researching various methods for efficiently checking if a key exists in a JSON file. The challenge I am facing is related to optimizing this process. My current workflow involves users uploading a CSV file which I then convert into JSON format ...

What measures can be taken in React to ensure that only authorized users are able to access the admin privileged layout

In a hypothetical scenario, imagine having a full-stack web application with an admin-dashboard on the front-end side. Now, let's say I am NOT an admin, but I attempt to access a route like /api/admin/dashboard Within the React app, there is authent ...

Personalize the marker design within the Wikitude SDK using JavaScript

Currently, I am developing an augmented reality view in Android using the wikitude-sdk. As part of the project, I am displaying markers on the screen and now I am looking to customize the marker view using the AR.HtmlDrawable method offered by the ...

Encountered a connection error in the Spring Boot application: net::ERR_CONNECTION_REF

Currently working on a school project developing a Spring Boot application using Restful. The application runs smoothly locally, but when deployed to AWS, I am encountering an "net::ERR_CONNECTION_REFUSED" error for all my GET and POST requests sent to the ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

The onsubmit event in Javascript activates the parent's onclick event

On my HTML page, I have a table with a form in each row. Clicking on the row should open a detail page, but clicking within the form should not trigger this action. Here is an example of what my row looks like: <tr onclick="window.parent.location.href ...

Mac OS reports an Illegal instruction: 4 error when running NodeJS

Each time I try to execute my program, it gives me an Illegal instruction: 4 error without any clue as to why. The code snippet in question: glob('/path/music/*.mp3', function(error, files) { for(var i = 0; i < files.length; i++) { songs ...

Searching for ways to filter out specific tags using regular expressions

Can anyone provide a quick solution to help me with this issue? I am trying to remove all html tags from a string, except for the ones specified in a whitelist (variable). This is my current code: whitelist = 'p|br|ul|li|strike|em|strong|a', ...

How come changes to the DOM are not recognized by subsequent DOM readings?

As I work on my Vue application, I have encountered a scenario involving an element with a data-range attribute defined as follows: :data-range="form.appearence.height_min + '/7'" The value of form.appearance.height_min is dependent on ...

Looking for a way to efficiently retrieve results by matching multiple string keywords as you go through each line of a file (fs)?

Essentially, I have multiple search strings provided by the client that need to be matched with each line in a file. If a line matches all of the inputted strings, I should add that line to the results array. However, when I run the code below, it only ret ...

Sometimes, React doesn't cooperate properly in the callback function of a setState operation

Imagine this scenario: callback = () => { ... } When is it appropriate to use this.setState({...}, this.callback); and when should I opt for this.setState({...}, () => { this.callback(); }); In order to maintain the validity of this within the ...

What is the best way to insert an iframe using getElementById?

I am looking to make some changes in the JavaScript code below by removing the image logo.png lines and replacing them with iframe code. currentRoomId = document.getElementById('roomID').value; if ( document.getElementById('room_' + c ...

Tips for passing input fields from a React Function component to a function

How can I retrieve the values from 4 input fields in my react functional component using a function called contactMeButtonPressed? The inputs include name, email, company name, and message when the contact me button is clicked. Do I need to implement stat ...

Contrasting the utilization of Angular $scope dependency with independent usage

As I delve into Angular, there's something that puzzles me. Being a newcomer to Angular, I recall a tutorial where they employed this syntax for applying properties to a controller's scope: app.controller('someCtrl', function(){ ...

My NodeJS MongoDB application is being bombarded by an infinite loop of "Sending request..." messages from the Postman

This is the complete code for my chatbot application const express = require('express'); const app = express(); const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const bodyParser = require(& ...