'Typescript method always returning undefined nested array

I am trying to write a Typescript method for a minesweeper game that looks if the neighbours of a field are mines and I get the same error everytime:

Uncaught TypeError: Cannot read properties of undefined (reading '5')
  private getNeighbours(field: Field[][]): number[][]{
        let mineNeighbours: number[][] = new Array(field.length)
            .fill(0)
            .map(() => new Array(field.length).fill(0));

        for (let i = 0; i < field[0].length; i++){
            for (let j = 0; j < field[1].length; j++){
                for (let yOffset = -1; yOffset < 2; yOffset++){
                    for (let xOffset = -1; xOffset < 2; xOffset++){
                        if (!(i + yOffset < 0 || i + yOffset > field[0].length || j + xOffset < 0 || j + xOffset < field[1].length || xOffset == 0 || yOffset == 0)){
                            if (field[i + yOffset][j + xOffset] instanceof Mine){
                                mineNeighbours[i][j]++;
                            }
                        }
                    }
                }
            }
        }
        return mineNeighbours;
    }

the error is coming from the line where I check if the current field is an instance of Mine

I tried to debug it thinking that I had passed an undefined agrument but that is not the problem. My guess is that there is something wrong in the if sentence above the checking of the mines. The method should return an int array with the count of neighbours of each field.



Solution 1:[1]

Your error will be in your if statement

let validY = i + yOffset >= 0 || i + yOffset < field[0].length;
let validX = j + xOffset >= 0 || j + xOffset < field[1].length;
let isDifferentCell = xOffset !== 0 && yOffset !== 0;

if( validY && validX && isDifferentCell ) {
    if (field[i + yOffset][j + xOffset] instanceof Mine){ // Also is there a reason why this needs to be checked can the field value not be an instance of Mine? I would remove this if its always going to be a Mine
        mineNeighbours[i][j]++;
    }
}

This cleans it up a bit better so it's easier to read ( big if statements like that can get confusing ). I believe your issue was you were double checking each x and y separately. so it was possible was invalid index but the other was not.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Derek Lawrence