Find sum of neighbors in a 2D array Write a function that takes 2 inputs:


a matrix, for example 2-dimensional array, and 
indices, for example [row, col] 


This function should return the sum of all the second input's neighbors (up, down, left, right, diagonals).

Below is my solution. Just wanted to know if there is a better way to solve this problem. And also wanted to know if I am covering all the edge cases.

function findingNeibors(myArray, i,j) {

let rowLimit = myArray.length-1;
let columnLimit= myArray[0].length-1;
let sum = 0;

if(i&lt;0 || j&lt; 0) {
    console.log("invalid Index")
    return
  };

if(i&gt;rowLimit || j&gt; columnLimit){
    console.log("You are Out Of Bound");
    return;
}

  for(let x = Math.max(0,i-1); x&lt;=Math.min(i+1,rowLimit); x++){
  for(let y = Math.max(0,j-1); y&lt;=Math.min(j+1,columnLimit); y++){
    if(x!==i || y!==j){
        console.log(myArray[x][y]);
        sum+=myArray[x][y];
    }
    }
  }
  return sum;
}


let input = [
  [0,1,2,3,4],
  [1,2,3,4,5],
  [2,3,4,5,6]
]


findingNeibors(input,0,0);
findingNeibors(input,2,2,0);
findingNeibors(input,-1,3);
findingNeibors(input,3,4);

```
Don't return if there is an error, throw the error.

if(i&lt;0 || j&lt; 0) {
    throw new Error("Invalid Index");
}

if(i&gt;rowLimit || j&gt; columnLimit){
    throw new Error("Index out of bounds");
}




Don't assume an array has elements

(i.e.: let columnLimit= myArray[0].length-1; will throw a TypeError if there are no elements in the list)

Play it safe.

//get first element in list, 
//if it doesn't exist set it to a default empty array
const [column = []] = myArray;
const columnLimit = column.length;




const before let and let before var

When declaring variables, always define them with const by default. You only use let when you expect that variable in question is likely to mutate. And never use var unless you have a good reason to.

Note: const arr = []; arr.push(1) mutates the array but not the variable




  am I covering all the edge cases ?


Yes, you are.

Assuming that the two dimensional array has columns of equal length




  Just wanted to know if there is a better way to solve this problem


There are only 8 elements max possible around a single element, and yet for every element you check to see if (i,j) != (x,y).

To solve this "problem", simply add all values (even with (i,j))

Then before returning subtract the element at (i,j)

for(let x = Math.max(0,i-1); x&lt;=Math.min(i+1,rowLimit); x++){
  for(let y = Math.max(0,j-1); y&lt;=Math.min(j+1,columnLimit); y++){
        sum+=myArray[x][y];
   }
 }

return sum - myArray[i][j]


Is this better? Well, it's 9 additional conditions VS an extra addition and subtraction.