Converting CSV data to Javascript arrays was already discussed here, but this is another case.
Assuming we have CSV-formated data structured like this:
one,two
three,four
five,six
We can use split() function or libraries like jquery-csv or Papa Parse to convert it into a JS array structured like:
[['one', 'two'], ['three', 'four'], ['five', 'six']]
But how to convert it into arrays containing data of first and second 'column' respectively? Like:
[['one', 'three', 'five'], ['two', 'four', 'six']]
We can, of course, iterate through obtained key-value pair arrays and push keys and values into separate arrays, but is there a way to get it structured like this directly from CSV?
Parsing CSV data into an array can be resource hungry enough, so it is good to skip unnecessary actions.
-
The term you're looking for is "pivot" (or "transpose"). CSVs are inherently row-oriented, so the first output makes sense, but I'm sure somewhere you can find an example of pivoting a 2d JS array. No sense reinventing the wheel, here. Also, because of how linear data works, you can't even do what you're asking for efficiently without the temporary structure.David Ehrmann– David Ehrmann2015年05月05日 09:44:39 +00:00Commented May 5, 2015 at 9:44
1 Answer 1
You can use below function to transpose your array:
transpose = function(a) {
// Calculate the width and height of the Array
var w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
// In case it is a zero matrix, no transpose routine needed.
if(h === 0 || w === 0) { return []; }
/**
* @var {Number} i Counter
* @var {Number} j Counter
* @var {Array} t Transposed data is stored in this array.
*/
var i, j, t = [];
// Loop through every item in the outer array (height)
for(i=0; i<h; i++) {
// Insert a new row (array)
t[i] = [];
// Loop through every item per item in outer array (width)
for(j=0; j<w; j++) {
// Save transposed data.
t[i][j] = a[j][i];
}
}
return t;
};
transpose([['one', 'two'], ['three', 'four'], ['five', 'six']]);
source: http://www.shamasis.net/2010/02/transpose-an-array-in-javascript-and-jquery
5 Comments
get function that does the mapping dynamically, but that makes accesses kinda slow, and it's more of a "cute" approach than a pragmatic one.