0

I have a 2d array similar to this:

var array = [
  {100,200},
  {200,200},
  {100,400}
];

Now I want to find if a known array exists inside the 2d array. For example, I want to check if [200,200] exists as a 2nd level array inside the 2d array.

On 1d arrays in the past I've used something like:

if (value in array) {...}

Can't seem to get that method working on 2d. What is the best solution?

CaribouCode
  • 13,998
  • 28
  • 102
  • 174

2 Answers2

0

Not sure if you already know but your syntax is not correct. It should look like this:

var array = [
  [100,200],
  [200,200],
  [100,400]
];

A naive way to check if [200, 200] exists as a 2nd level array:

console.log(array[1][0] == 200 && array[1][1] == 200);

Another naive approach is to use a nested loop and go through each item.

If you want a fast approach to this, you might want to read up on search algorithms. Searching Algorithms

Quinn
  • 458
  • 2
  • 8
  • If I knew the specific point in the array to check i.e. array[1][0] = 200, the chances are I already know it's in there! I need to be able to search the entire 2d array for these values. – CaribouCode Apr 10 '14 at 01:10
0
var array = [
    [100,200],
    [200,200],
    [100,400]
];

var searchFor = [200,200];

function arrayExistsInside(haystack, needle) {
    for(var i = 0; i < haystack.length; i++) {
        if(compareArray(haystack[i], needle)) return true;
    }
    return false;
}

function compareArray(array1, array2) {
    if(array1.length != array2.length) return false;

    for(var i = 0; i < array1.length; i++) {
        if(array1[i] != array2[i]) return false;
    }

    return true;
}

if(arrayExistsInside(array, searchFor)) { ... }

You could also use the compare function outlined on How to compare arrays in JavaScript?

Community
  • 1
  • 1
Jason
  • 734
  • 1
  • 7
  • 17