Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript get diagonals of array

function getDiagonals(grid) {
    let result = [];
    let Ylength = grid.length;
    let Xlength = grid[0].length;
    let maxLength = Math.max(Xlength, Ylength);
    let temp;
    for (let k = 0; k <= 2 * (maxLength - 1); ++k) {
        temp = [];
        for (let y = Ylength - 1; y >= 0; --y) {
            let x = k - y;
            if (x >= 0 && x < Xlength) {
                temp.push(array[y][x]);
            }
        }
        if (temp.length > 0) {
            result.push(temp);
        }
    }
  
  return result;
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #javascript #diagonals #array
ADD COMMENT
Topic
Name
2+6 =