0

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.

1
  • 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. Commented May 5, 2015 at 9:44

1 Answer 1

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']]);

jsfiddle

source: http://www.shamasis.net/2010/02/transpose-an-array-in-javascript-and-jquery

Sign up to request clarification or add additional context in comments.

5 Comments

And if the file has 1000 lines ?
@PedroLobito: It only changes the runtime and memory requirements by a constant factor. This usually isn't a problem.
You could also use a custom 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.
That is indeed my point. This code is fine if CSV is small, so it doesn't matter if we first convert it to key-value array of arrays and then use code like this to pivot it. I agree that key-value formatting is in most cases more logical, but if for some reason we need separate arrays for keys and values and the CSV is rather big, then it would be better to have a way do one processing and obtain separate arrays directly from CSV.
Anyway, this seems to be as good as it gets. Thanks everyone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.