'cant access index in previous array

I am trying to compare grid[i][j] with the index directly above it, then return all of the values that are different. So if grid[i][j] does not match the one above it, the code should return grid[i][j].

I thought that [i-1] would work (directly below👇 ), but i am just getting an error of cannot read properties of undefined.

if(grid[i][j] !== grid[i-1][j]){
                        return grid[i][j]
                    }

Here is the test case:

[["1","0","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]

below is the code that i have written:

var numIslands = function(grid) {
        for(let i = 0; i < grid.length; i++){
            for(let j = 0; j < grid.length; j++){
                let ans = 0;
                if(grid[i][j] === '1'){
                    if(grid[i][j] !== grid[i-1][j]){
                        return grid[i][j]
                    }
                }
                
            }
        }
    };


Solution 1:[1]

Does this match your desired output?

let x = [                    // Expected Outputs:
  ["1", "0", "1", "1", "0"], // _, 1, 0, _, _
  ["1", "1", "0", "1", "0"], // _, _, _, 0, _
  ["1", "1", "0", "0", "0"], // 0, 0, _, _, _
  ["0", "0", "0", "0", "0"]  // = 1, 0, 0, 0, 0
]
for (let i = 0; i < x.length; i++) {
  let lower = x.slice(i + 1, i + 2)
  for (let j = 0; j < x[0].length; j++) {
    if (!lower.length) {
      continue
    }
    if (lower[0][j] != x[i][j]) {
      console.log(lower[0][j])
    }
  }
}

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 BeRT2me