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
}
3

4 Answers 4

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));
Sign up to request clarification or add additional context in comments.

Comments

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]);

Comments

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;
}

Comments

-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) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.