2

I know I'm missing something obvious, but I can't seem to find my mistake. I want to see if an array is within another two dimensional array. Here's my code:

var cell = [0, 0];
var population = [[0, 0], [1, 1]];

if (cell == population[0]) {
    alert("Cell found within population");
}
else if ([0, 0] == population[0]) {
    alert("Array found within population");
}
else {
    alert("Neither found within population");
}

I used the second conditional just to be sure that the value of cell and population[0] weren't equivalent. But as it turns out, neither of them match. I've tested (cell[0] == population[0][0]), and that seems to work.

I would appreciate any clarification. Thanks!

Alex Krycek
  • 205
  • 1
  • 7

4 Answers4

3

The issue here is that the == operator for arrays in javascript compares memory addresses rather than the actual values. This is why you notice that (cell[0] == population[0][0]) returns true (you're comparing values).

You should iterate through the elements in the arrays to compare them. Here's an example of what I mean.

function checkEquivalence(arr1, arr2){
    if(arr1.length != arr2.length) 
        return false;     
    for (i = 0; i < arr2.length; i++)
    {
        if(arr1[i] != arr2[i])
           return false;
    }
    return true;
}

Now you can run the operation checkEquivalence( cell, population[0] );

Kiran Ryali
  • 1,371
  • 3
  • 12
  • 18
0

Unfortunately you can't compare arrays directly, you must compare them element-by-element like this:

function compareArrays(arrayOne, arrayTwo) {
    if (arrayOne.length != arrayTwo.length) {
        return false;
    }
    for (var i = 0; i < arrayOne.length; ++i) {
        if (arrayOne[i] != arrayTwo[i]) { 
             return false;
        }
    }
    return true;
}

Now you can use:

compareArrays([0, 0], population[0])

...which will yield true.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

You probably need some sort of deep equality comparison to see if two objects (including arrays) are "equal" by value. Take a look at Object comparison in JavaScript, or google for Javascript deep equality.

Community
  • 1
  • 1
Bobby Eickhoff
  • 2,585
  • 2
  • 23
  • 22
0

If your comparisons are always going to be this simple, a hackish work around would be:

if(cell.valueOf() == population[0].valueOf())  {
    ...
}

The above would effective compare two strings, changing the logic to:

if('0,0' == '0,0') {
    ...
}

Definitely not recommend best-practices by anyone I work with, but is useful in extremely controlled situations.