Skip to content Skip to sidebar Skip to footer

Evaluating Javascript Arrays

I have an array that contains an array of arrays if that makes any sense. so for example: [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] I want to see whether an array exists within

Solution 1:

Comparing the two arrays using == or === will not work because they are not the same object. If you want to determine the element-wise equality of two arrays you need to compare the arrays element-wise.

I doubt you'll gain anything from using tricks like join(',') and then using string operations. The following should work though:

function arraysAreEqual (a, b) {
  if (a.length != b.length) {
    returnfalse;
  }

  for (var i=0; i<a.length; i++) {
    if (a[i] != b[i]) {
      returnfalse;
    }
  }

  returntrue;
}

function containsArray (arrays, target) {
  for (var i=0; i<arrays.length; i++) {
    if (arraysAreEqual(arrays[i], target)) {
      returntrue;
    }
  }

  returnfalse;
}

var arraysToSearch = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]];
var newArray = [1, 2, 3];
containsArray(arraysToSearch, newArray);

Solution 2:

I've often found that the best way to compare two arrays is to compare their join values.

if(newArray.join('/') == entry.join('/')) ...

Additionally, you may want to throw in one more check:

if(newArray.length == entry.length && newArray.join('/') == entry.join('/'))

If the length check is invalidated, that's a really quick way of invalidating the comparison and not bother with doing the joins, but the check also improves the reliability of the comparison. For instance, without the length check, the following arrays would yield the same result when joined:

var a = [1, '2/3'];
var b = [1, 2, 3];

With the length check, you're sure something like this can't happen, and don't have to worry about escaping delimiters or anything...

Solution 3:

Unfortunately, in the general case, the only way you can tell if arrays are equal in this sense is to compare their elements. There's no shortcut or built-in way of doing that.

In some special cases you can make your life a bit easier by using Array#join and comparing the resulting strings, e.g.:

var a = [1, 2, 3];
var b = [1, 2, 3];
alert(a.join(",") == b.join(",")); // Alerts "true"

...because a.join(",") results in the string "1,2,3", as does b.join(","). But obviously you can only do that when you know that you can concatenate and compare the values meaningfully like that. Doing this may (may) be faster because you can leverage the JavaScript interpreter's internal join and string comparison methods, but again, you can't do this in the general case, only when you know the data in the array is going to be okay with being turned into a string and concatenated like that.

Solution 4:

You need to write a helper method that compares 2 arrays element by element and use that instead of ===.

Solution 5:

The code in this answer fails to differentiate the examples in:

javascript:
function sameRAs(newArray,entry){
     return newArray.length == entry.length &&
                                  newArray.join('/') == entry.join('/')};
     alert( sameRAs(  [1,'2/3',4],  [1,2,'3/4']  )  ?  'same' : 'different' );
     alert( sameRAs(    [null],         [,]      )  ?  'same' : 'different' );

To see that [null] and [,] are indeed different, consider:

 javascript:  alert( [null][0] );  alert( [,][0] );

which display null and undefined respectively.


A composited array can check array identity! with == for identical arrays!

javascript:
      ra=[1,2,3]; ar=[4]; r=[]; composite=[ar,r,ra,ar,ra];
      for(i in composite)
         if(composite[i]==ra)
            alert( JSON.stringify(composite) +' at ['+ i +']'+' == ['+ ra +']')

displays:

[[4],[],[1,2,3],[4],[1,2,3]] at [2] == [1,2,3]

and

[[4],[],[1,2,3],[4],[1,2,3]] at [4] == [1,2,3]

While my vote is with .toSource() (& Mozilla), simple valued arrays can be compared via JSON.

javascript:
      ra=[1,2,3]; ar=[1,2,3];
      alert([  ra==ar,   JSON.stringify(ra)==JSON.stringify(ar)  ]);

displays false,true.


Another wrinkle: circular arrays. Comparing these is difficult, which is where .toSource() shines.

javascript:
   ra = [0,1,2];   ra[3] = ra;      r2d2 = #2= [0,1,2,#2#];
   alert([ ra==r2d2,  ra.toSource() == r2d2.toSource() ])

displays false,true (in FireFox).


Regarding machine efficiency: the computational expense is marginal compared to the cost invested in human time. Computers are here to reduce human labour, not the other way around. Truly computationally expensive and extensively deployed computations may warrant a large investment in human labour to realize efficiencies. This is not one of those times.

The simplicity of .toSource() might payoff by installing FF as a pragmatic approach to solving problems such as this. The scale of a problem often means coercing the environment and machinery to get a solution rather than using human labour.

Post a Comment for "Evaluating Javascript Arrays"