js get column from array code example

Example 1: javascript array column

//get column in javascript... 

	function getCol(matrix, col){
       var column = [];
       for(var i=0; i<matrix.length; i++){
          column.push(matrix[i][col]);
       }
       return column; // return column data..
    }

    var array = [new Array(20), new Array(20), new Array(20)]; //..your 3x20 array
    getCol(array, 0); //Get first column

Example 2: reach to each cell in 2d array javascript

// ... Matrix declaration goes here

function getCell(matrix, y, x) {
  var NO_VALUE = null;
  var value, hasValue;
  
  try {
    hasValue = matrix[y][x] !== undefined;
    value    = hasValue?  matrix[y][x] : NO_VALUE;
  } catch(e) {
    value    = NO_VALUE;
  }

  return value;
}

function surroundings(matrix, y, x) {
  // Directions are clockwise
  return {
    up:        getCell(matrix, y-1, x),
    upRight:   getCell(matrix, y-1, x+1),
    right:     getCell(matrix, y,   x+1),
    downRight: getCell(matrix, y+1, x+1),
    down:      getCell(matrix, y+1, x),
    downLeft:  getCell(matrix, y+1, x-1),
    left:      getCell(matrix, y,   x-1),
    upLeft:    getCell(matrix, y-1, x-1)
  }
}

Tags:

Java Example