Search code examples
javascriptnested-loopsmultidimensional-array

Using the Array methods with nested (multidimensional) arrays?


I am having problems when using Array methods with nested arrays.

var map = [
        ["Blank", "Blank", "Blank"],
        ["Blank", "Player", "Blank"],
        ["Blank", "Blank", "Blank"]
];

for (i=0; i<map.length; i++) {
        for (j=0; j<map[i].length; j++) {
            var playerY = map[i][j].indexOf("Player");
        }
}

console.log(playerY);

This will always log -1 which is I know an error. Although I think my issue is with using nested arrays. It could also be a problem with the way I am using .indexOf(), or the way I am looping through the arrays. Thank you for helping. Any advise would be appreciated! :)

EDIT: Thank you for all the help. I ended up changing things a lot and not using the .indexOf() method all together. Here is what I ended up doing.

var map = [
        ["Blank", "Blank", "Blank"],
        ["Blank", "Player", "Blank"],
        ["Blank", "Blank", "Blank"]
];

for (x = 0; x < map.length; x++) {
    for (y = 0; y < map[x].length; y++) {
        if (map[x][y] == "Player") {
            console.log("(" + x.toString() + ", " + y.toString() + ")");
        }
    }
}

Solution

  • The loop doesn't stop when indexOf finds "Player" inside the nested array. It will continue to loop, thus overwriting the value of playerY with each iteration. To fix this, we must break when indexOf has found the string:

    for (i = 0; i < map.length; i++) {
        for (j = 0; j < map[i].length; j++) {
            var playerY = map[i][j].indexOf("Player");
    
            if (playerY > -1) break; // We have found "Player"
        }
    }