-5

I have a the following dict I would like to transpose:

dict = {
         'column1': [1, 2, 3],
         'column2': [4, 5, 6],
         'column3': [7, 8, 9]
        }

Into:

transposed_array = [
                    [1, 4, 7],
                    [2, 5, 8],
                    [3, 6, 9]
                  ]
serkan
  • 6,885
  • 4
  • 41
  • 49
Below the Radar
  • 7,321
  • 11
  • 63
  • 142

3 Answers3

1

Here's a solution (updated for non square matrices):

var dict = {
     'column1': [1, 2, 3],
     'column2': [4, 5, 6],
     'column3': [7, 8, 9]
}
var keys = Object.keys(dict);
var transposedMatrix = dict[keys[0]].map(function(col,i){  
  return keys.map(function(_,j){ return dict[keys[j]][i] })
});

Demonstration

Note that this code assumes that objects do have ordered keys, which has always been the case in all known ES implementations and is now normalized by ES6.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1
var dict = {
         'column1': [1, 2, 3],
         'column2': [4, 5, 6],
         'column3': [7, 8, 9]
        };
var transposed_array =[];
for (key in dict){
    transposed_array.push(dict[key]);

}
console.log(transposed_array);  

Demo
Updated:

var dict = {
         'column1': [1, 2, 3],
         'column2': [4, 5, 6],
         'column3': [7, 8, 9]
        };
var transposed_array =[];
for (key in dict){
    transposed_array.push(dict[key]);

}
function transposeArray(array){

    var newArray = [];
    for(var i = 0; i < array.length; i++){
        newArray.push([]);
    }

    for(var i = 0; i < array.length; i++){
        for(var j = 0; j < array[i].length; j++){
            newArray[j].push(array[i][j]);
        }
    }

    return newArray;
}
console.log(transposeArray(transposed_array));  

Demo

ozil
  • 6,930
  • 9
  • 33
  • 56
1

basically first find the shared part of the keys, then the endings, after sort reassamle the array. the result is numerical orderd if number otherwise the order is maintained.

var dict = {
        'column3': [7, 8, 9],
        'column2': [4, 5, 6],
        'column1': [1, 2, 3]
    },
    keys = Object.keys(dict),
    samePart = keys.reduce(function (a, b) {
        var i = 0, l = Math.min(a.length, b.length);
        while (i < l && a[i] === b[i]) { i++; }
        return a.substr(0, i);
    }),
    otherPart = keys.map(function (e) { return e.slice(samePart.length); }).sort(function (a, b) { return a - b; }),
    transposedMatrix = [].map.call(otherPart, function (col, i) { return dict[samePart + col].map(function (_, j) { return dict[samePart + col][j]; }); });
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392