How do I traverse an array diagonally in javascript [closed]

From top left to bottom right

var theArray = ["ABCD","EFGH","IJKL"];

var length = { "x" : theArray[0].length, "y" : theArray.length };
length.max = Math.max(length.x, length.y);

var temp, k, x, y;

for (k = 0; k <= 2 * (length.max - 1); ++k) {
    for (temp = [], y = length.y - 1; (x = k - y), y >= 0; --y) {
        x >= 0 && x < length.x && temp.push(theArray[y][x]);
    }
    temp.length > 0 && (document.body.innerHTML += temp.join('') + '<br>');
}

(see also this Fiddle)


From the bottom left to top right

var theArray = ["ABCD","EFGH","IJKL"];

var length = { "x" : theArray[0].length, "y" : theArray.length };
length.max = Math.max(length.x, length.y);

var temp, k, x, y;

for (k = 0; k <= 2 * (length.max - 1); ++k) {
    for (temp = [], y = length.y - 1; (x = k + y - length.y), y >= 0; --y) {
        x >= 0 && x < length.x && temp.push(theArray[y][x]);
    }
    temp.length > 0 && (document.body.innerHTML += temp.join('') + '<br>');
}

(see also this Fiddle)


Combined

As there’s but a single line of difference between both, you can easily combine them in a single function :

var theArray = ["ABCD","EFGH","IJKL"];

function diagonal(data, fromBottom) {
    var length = { "x" : data[0].length, "y" : data.length };
    length.max = Math.max(length.x, length.y);

    var temp, k, x, y;

    var returnMe = [];

    for (k = 0; k <= 2 * (length.max - 1); ++k) {
        for (temp = [], y = length.y - 1; y >= 0; --y) {
            x = k - (fromBottom ? length.y - y : y);
            x >= 0 && x < length.x && temp.push(data[y][x]);
        }
        temp.length > 0 && returnMe.push(temp.join(''));
    }
    return returnMe;
}

document.body.innerHTML = diagonal(theArray).join('<br>') +
                          '<br><br><br>' +
                          diagonal(theArray, true).join('<br>');

(see also this Fiddle)

Leave a Comment

tech