javascript – Check if a position exists in a two-dimensional array?

Question:

I have the following array:

var x = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

I have to check that the position exists inside the array. For example x[4][1] should be false, and x[2][2] should be true.

I did the following function:

function posicionValida(i,j){
  for (var i = 0; i < x.length; i++) {if (x[i]==undefined){
    return false}
      for (var j = 0; j < x.length; j++){
        if (x[j]==undefined){
          return false
  } else {return true} }}}

But it's not working. How could I do it?

Answer:

You can do it very simply by comparing the sizes of each dimension, if vertically i exceeds the length of x you send false, if you don't check j in the array x[i] , if it exceeds you send false, if not then the position exists:

Update: you can reduce the function to a single line and avoid negative numbers like this:

var x = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

posicionValida = (i,j) => i>=0 && j>=0 && i<x.length && j<x[i].length

console.log(posicionValida(2,2));
console.log(posicionValida(4,1));
console.log(posicionValida(1,5));
console.log(posicionValida(2,-2));

Previous answer:

var x = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];


function posicionValida(i,j){
  if(i>x.length)
    return false;
  if(j>x[i].length)
    return false;
  return true;
}

console.log(posicionValida(2,2));
console.log(posicionValida(4,1));
console.log(posicionValida(1,5));
Scroll to Top