Transpose 2d array (v2)

Revision 2 of this benchmark created on


Setup

var array = [
      [1,2,3],
      [4,5,6],
      [7,8,9],
      [10,11,12]
    ];

Test runner

Ready to run.

Testing in
TestOps/sec
For loops
var newArray = [],
    origArrayLength = array.length,
    arrayLength = array[0].length,
    i;
for(i = 0; i < arrayLength; i++){
    newArray.push([]);
};

for(i = 0; i < origArrayLength; i++){
    for(var j = 0; j < arrayLength; j++){
        newArray[j].push(array[i][j]);
    };
};
ready
Map
var newArray = array[0].map(function(col, i){
    return array.map(function(row){
        return row[i];
    });
});
ready
single loop
function transpose(arr,arrLen) {
  for (var i = 0; i < arrLen; i++) {
    for (var j = 0; j <i; j++) {
      //swap element[i,j] and element[j,i]
      var temp = arr[i][j];
      arr[i][j] = arr[j][i];
      arr[j][i] = temp;
    }
  }
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.