3

I stored several coordinate pairs in a single array. For example:

[[1,2],[4,5],[7,8]]

I'd like to find the coordinate pair that I got. I got coordinate:

[4,5]

If array contains this coordinates that I'll get true otherwise false. This is my code:

function isContain(coords) {
   for (let i = 0; i < array.length; i++) {
       if (array[i].length !== coords.length) return false;

       for (let j = 0; j < array[i].length; j++) {
           if(array[i][j] === coords[j]) {
               return true
           }
       } 
  }
  return false
}
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
javorkabotond
  • 39
  • 1
  • 6

4 Answers4

1

You can do something like this

const foo = [[1, 2], [4, 5], [7, 8]];
const coords = [4, 5];

function isContain(coords) {
  for (const f of foo) {
    if (f[0] === coords[0] && f[1] === coords[1]) {
      return true;
    }
  }
  return false;
}

console.log(isContain(coords));
Safi Nettah
  • 1,160
  • 9
  • 15
0

Since the coordinates always contains exactly two items, you don't need the inner loop, just compare the Xs and the Ys directly. Also use for...of:

function isContain(coords){
  for(let item of array) {
    if(item[0] == coords[0] && item[1] == coords[1]) {
      return true;
    }
  }
  return false
}

You can also use some instead like so:

let exists = array.some(item => item[0] == coords[0] && item[1] == coords[1]);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

If you are simply comparing numbers you could do convert to strings:

const isContain = coords =>
{
   for (let item of array)
   {
      if (item.split("") === coords.split(""))
         return true;
   }
   return false;
}
JayCodist
  • 2,424
  • 2
  • 12
  • 28
-1

Try

arr.some(e=> e==''+[4,5])

let a=[[1,2],[4,5],[7,8]]

let isContain = (arr) => arr.some(e=> e==''+[4,5]);

console.log( isContain(a) );
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345