Javascript Array myTranspose() method

Description

Javascript Array myTranspose() method


let arr = ([/*from w ww . j ava2s .c o  m*/
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
        ])

Array.prototype.myTranspose = function () {
  let result = [];

  for (let i = 0; i < this.length; i += 1) {      //THIS refers to the ARRAY
    result.push([]);

    for (let j = 0; j < this.length; j += 1) {
      result[i][j] = this[j][i];
    }
  }
  return result;
}

console.log(arr.myTranspose());

Javascript Array myTranspose()

Array.prototype.myTranspose = function() {
  let transposed = [];
  for (let i = 0; i < this.length; i += 1){
    transposed[i] = [];/*from w ww .jav  a 2s  . c o  m*/
    for (let j = 0; j < this[i].length; j += 1){
      transposed[i][j] = this[j][i];
    }
  }
  return transposed;
};

let arr = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
  ];

console.log(arr.myTranspose());

Javascript Array myTranspose()

Array.prototype.myTranspose = function() {
  for (let i = 0; i < this.length; i += 1){
    for (let j = 0; j < i; j += 1){
      var temp = this[i][j];
      this[i][j] = this[j][i];/*from ww  w.ja  v a2 s . c o m*/
      this[j][i] = temp;
    }
  }
  return this;
};

let arr = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8]
  ];

console.log(arr.myTranspose());

Javascript Array myTranspose()

Array.prototype.myTranspose = function () {
  const columns = [];/*  w w  w  . jav a  2s. c  om*/

  // build the array to push vals into
for (let i = 0; i < this[0].length; i++) {
  columns.push([]);
  }

  for (let i = 0; i < this.length; i++) {
    for (let j = 0; j < this[i].length; j++) {
      columns[j].push(this[i][j]);
    }
  }

  return columns;
};

console.log([[0, 1, 2], [3, 4, 5], [6, 7, 8]].myTranspose()); //[ [ 0, 3, 6 ], [ 1, 4, 7 ], [ 2, 5, 8 ] ]

Javascript Array myTranspose()

Array.prototype.myTranspose = function () {
  const result = new Array(this[0].length);

  for (let i = 0; i < result.length; i++) {
    result[i] = new Array(this.length);
  }/*from w  w  w.j  av  a  2s.  c om*/

  for (let row = 0; row < this.length; row++) {
    for (let col = 0; col < this[row].length; col++) {
      result[col][row] = this[row][col];
    }
  }

  return result;
};



PreviousNext

Related