Combining CSV data from multiple arrays into a single object array

After finding inspiration in this thread on storing CSV files in separate arrays, I successfully implemented it. Now, I am hoping to expand my setup by incorporating 8 additional arrays, each containing the contents of CSV files.

My main challenge now is how to combine all these arrays into a single array of objects. This is crucial for the next phase of utilizing these arrays effectively. The code snippet I have currently is displayed below, but I am uncertain if it is correct:

Any assistance or guidance on this matter would be greatly appreciated.

var dataCSV;
var dataCSV2;

var collection = {dataCSV, dataCSV2};

d3.csv("data/csv1.csv", function(data) {
    data.forEach(function(d) {
        d.word = d.word;
        d.frequency = +d.frequency;
})
    dataCSV = data;
    console.log(dataCSV);
});

d3.csv("data/csv2.csv", function(data) {
    data.forEach(function(d) {
        d.word = d.word;
        d.frequency = +d.frequency;
    })
    dataCSV2 = data;
    console.log(dataCSV2);
});

function merge(data1, data2) {
    collection = {data1, data2};
    console.log(collection);
}

merge(dataCSV, dataCSV2);

The desired output for the 'collection' should ideally be structured as follows:

collection {
    dataCSV {
        word: ..., frequency: ...,
        word: ..., frequency: ...
    },
    dataCSV2 {
        word: ..., frequency: ...,
        word: ..., frequency: ...
    }
 }

Answer №1

Enhance your code efficiency by consolidating repetitive tasks into a single method that fetches and formats data, returning a promise. Utilize promises to gather results from multiple promises with the help of Promise.all(). Subsequently, organize the collected data into arrays within an object for streamlined access.

Example (not verified):

const getCsv = (url) => new Promise((resolve) => {
  d3.csv(url, function(data) {
    data.forEach(function(d) { // Alternatively, use Array.map() for cleaner code
      d.word = d.word;
      d.frequency = +d.frequency;
    })

    resolve(data);
  });
});

Promise.all([ // Load and synchronize data from two CSV sources
  getCsv('data/csv1.csv'),
  getCsv('data/csv1.csv')
])
.then(([dataCSV, dataCSV]) => { 
  const collection = { dataCSV, dataCSV2 };
  console.log(collection );
});

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

Changing an object into an array for saving and transforming it back to an array for usage in JavaScript

I am dealing with a unique situation where I have an object created from dynamic checkboxes in Angular. The structure of the object looks like this: {"United States":true,"Canada":true,"Australia":false} While this format works well for storing values, I ...

Tips for replacing all occurrences of a specific string in HTML while preserving JavaScript attributes

Is there a way to use RegEx to replace part of an HTML document without affecting the root element or other elements like event listeners? Consider this scenario: for (; document.body.innerHTML.indexOf(/ea/) != -1;) { document.body.innerHTML = docu ...

Guide on entering text into a concealed text box using WebDriver and Java

When attempting to use sendkeys on an input field, I encountered a warning that puzzled me: org.openqa.selenium.InvalidElementStateException: Element must not be hidden, disabled or read-only (WARNING: The server did not provide any stacktrace informati ...

The positioning of the Kendo UI window is off-center

I have encountered a problem with the alignment of the Kendo Window. There is a simple fiddle available to demonstrate this issue. Despite having ample space for the Kendo window to show without triggering the browser's vertical scroll bar, the cente ...

Developing a JavaScript program for ATMs that can efficiently handle and dispense money in the fewest number of notes possible

When a certain amount is entered, the code should be capable of handling figures up to 20000. For instance, if the input amount is 2600 with a card balance of 3000, the output will be as follows: New Balance - 400 Notes: 2000 * 1 500 * 1 100 * 1 Only thre ...

The issue arises when the jQuery $.get() method fails to deliver the expected response to the client, despite returning a status code of

I am having trouble with sending a REQUEST to a server in order to retrieve a message. I have tried using the jQuery method $.get(), and it seems to have successfully reached the server. However, I am facing an issue where I am unable to send a RESPONSE b ...

How to Utilize Output() and EventEmitter() for Value Transmission in Angular Application

Last week I was successfully able to implement Output() and EventEmitter() in my Angular app. However, today I am facing a new challenge while trying to apply the same concept in a different scenario. I'm not sure what I might be overlooking. Firstly ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...

Avoid activating the hover state

Is there a way to prevent a button, div, or li from hovering if it already has an active status using CSS? #list-of-tests .item-test:hover:not(.active) { background-color: #4d5f75; border: solid 1px #4d5f75; } #list-of-tests .item-test:active { ...

Conceal button divider on pager in Jqgrid

Within my grid setup, there are 3 buttons placed in the pager section: 'Refresh', 'Constution', and 'Developed'. These buttons are separated by two vertical navSeparators. Upon grid load, the 'Developed' button is hi ...

The rule 'import/no-cycle' definition could not be located

After removing my npm package along with the package.lock.json file, I proceeded to run 'npm install' and followed up with 'npm update'. However, upon starting my application using 'npm run start', an error occurred. Upon lau ...

A guide to traversing a class and pinpointing each element that contains a particular classlist property

Here is my code snippet that generates 4 spans within a class. When a user clicks on a span, it changes color to indicate that it has been clicked. <head> <style> .tagger1010 span { padding: 6px 10px; ...

Iterate through an Array of Objects and exhibit a single object property in HTML one at a time by utilizing Javascript

I am working with an array of objects that contain two properties: "quote" and "author". I have a container div where I want the quotes to be displayed one by one at an interval of every 2 seconds. Currently, it is showing one letter at a time instead of d ...

Guide on modifying cube material dynamically in WebGL at runtime

Currently, I am utilizing three.js to create animations. My goal is to dynamically modify the material of a cube mesh. Below is an example: // Create cube geometry var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....]; var geometry = new ...

The shadow feature in Three.js doesn't seem to be functioning properly

I'm having trouble getting the Three.js shadow effect to work in version r82. I believe I have everything set up correctly, but for some reason it's not working. Can anyone point out what I might be missing? Here is an example link for referen ...

What is the best way to transfer data from Material UI to Formik?

I'm facing an issue when trying to integrate a Material UI 'Select' component into my Formik form. It seems like I am unable to pass the selected values from the Material UI component to Formik's initialValues. const [selectedHours, se ...

The function contacts.map is not defined

Can someone help me understand why I am getting the error message "contacts.map is not a function"? I am working on fetching data from a contacts array list that I have created. My goal is to display buttons inside a panel. When a button is clicked, the sc ...

javascript basic image carousel

How can I modify my slider so that "slide 1" appears after "slide 3" without needing to use the return or previous button each time? I'm not very well-versed in javascript, so I thought I'd reach out for some assistance ...

What is the reason that the Angular foreach loop does not allow the use of break or return to exit the loop?

When I noticed that the Angular foreach loop is similar to the enhanced for loop in Java, I assumed I could use a break or return statement to exit the loop. However, I soon discovered that this wasn't possible. I'm curious about the reasoning be ...

The ASP.NET Core MVC controller encounters a null input parameter when called by an ajax request

Here is the scenario involving an ajax call: ... $("#testBtn").click(function (e) { e.preventDefault(); $.ajax({ url: "/profile/GuestList", data: {"keytype": "1"}, method: "POST&q ...