Last active
August 29, 2015 14:22
-
-
Save JakeSidSmith/c95d4fff60d84a94f5ab to your computer and use it in GitHub Desktop.
Flip a table from columns to rows & vice versa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
# 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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var output = _.zip.apply(undefined, table);