'Copy a specific column from a csv file to an array using javascript
I have a little problem that is how to Copy a specific column from a csv file to an array using javascript
thank you :)
Solution 1:[1]
csv data is best represented in javascript using an array of arrays (a 2-dimension array) with primary indices representing rows (records in data-base terminology) and the inner indices representing column cells for that row (fields in data-base terminology).
Thus, this csv data:
"name","age","height"
"John",22,1.9
"Jane",21,1.9
"Joe",23,1.8
would be represented as:
[["name","age","height"],["John",22,1.9],["Jane",21,1.9],["Joe",23,1.8]];
in a javascript array.
If you have an array like that, you can extract a column (the first column, inner array index [0] in this case, easily with:
const columnArray = [];
for (let i=0; i<csvArray.length; i++){columnArray.push(array1[i][0])}
// columnArray now holds ["name","John","Jane","Jo"];
// use [1] instead of [0] for the second column, [2] for the third, etc.;
If you don't yet have the array, you will have to form one. Many frameworks may do this for you but it is easily achieved once you have the csv data inside a variable:
const csvFileData = // read from textarea or file;
const csvArray = csvFileData.split('\n')
// csvArray holds ['"name","age","height"', '"John",22,1.9', '"Jane",21,1.9', '"Joe",23,1.8'] at this stage;
// split the inner arrays to arrays of cell data;
for (let i=0; i<array1.lengthl; i++){array[i]=array[i].split(',')}
// We've replaced each element with an array holding the component cells of what was previously a row;
// csvArray now holds:
[["name","age","height"],["John",22,1.9],["Jane",21,1.9],["Joe",23,1.8]];
That final array can now be processed to extract the required column as shown above.
Finally, all this assumes you can get the csv data into a variable (remember it has line breaks). Fetch() is probably the standard way but a simple (if dirty) alternative I often use is to assign the value of an html textarea into which I have pasted the csv file contents into, directly to a variable:
const csvFileData = document.getElementById('textareaOnWebPage').value;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dave Pritlove |
