Skip to content

Instantly share code, notes, and snippets.

@JakeSidSmith
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakeSidSmith/c95d4fff60d84a94f5ab to your computer and use it in GitHub Desktop.
Save JakeSidSmith/c95d4fff60d84a94f5ab to your computer and use it in GitHub Desktop.
Flip a table from columns to rows & vice versa
/*
# Flip a table from columns to rows & vice versa e.g.
var table = [
['Date', 'Jan', 'Feb', 'Mar', 'Apr', 'May'],
['Data 1', 45, 63, 68, 44, 86],
['Data 2', 57, 74, 15, 44, 53],
['Data 3', 47, 37, 76, 64, 62]
];
...becomes...
var table = [
[Date, Data 1, Data 2, Data 3]
[Jan, 45, 57, 47]
[Feb, 63, 74, 37]
[Mar, 68, 15, 76]
[Apr, 44, 44, 64]
[May, 86, 53, 62]
];
Requires underscore (but could be replaced with standard for loop)
Could probably be improved with _.reduce
*/
var tableFlip = function (arr) {
var newArr = [];
_.each(arr, function (row, rowIndex) {
_.each(row, function (cell, cellIndex) {
if (!newArr[cellIndex]) {
newArr[cellIndex] = [];
}
newArr[cellIndex][rowIndex] = cell;
});
});
return newArr;
};
/*
It's actually recommended that you use _.zip like so...
table = _.zip.apply(null, table);
...but this returns undefined values if some of your rows / columns are of different length,
whereas my function will not define values that are not present
*/
@AngryLawyer
Copy link

var output = _.zip.apply(undefined, table);

@JakeSidSmith
Copy link
Author

Added as comment. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment