Comparing an array in javascript

I have two arrays: a = [1,2,3]andb=[1,2,3]

if I do (a==b), it returns false. how to compare two arrays with the same values?

a[0]==b[0] will return true, but how can we compare two arrays instead of two identical elements inside two different arrays?

+5
source share
8 answers

If you want to compare 2 arrays you can use JSON.stringify

JSON.stringify([1,2,3]) === JSON.stringify([1,2,3]); //=> true

It also compares [nested] objects inside an array or [nested] arrays in an array:

JSON.stringify([1,2,3,{a:1,b:2}]) === 
  JSON.stringify([1,2,3,{'a':1,b:2}]); //=> true

JSON.stringify([1,2,3,{a:1,b:2,c:{a:1,b:2}}]) === 
  JSON.stringify([1,2,3,{'a':1,b:2,c:{a:1,b:2}}]); //=> true

JSON.stringify([1,2,3,{a:1,b:2,c:[4,5,6,[7,8,9]]}]) === 
  JSON.stringify([1,2,3,{'a':1,b:2,c:[4,5,6,[7,8,9]]}]); //=> true

In this jsfiddle , I played a little with the idea

+1
source

You have 2 options.

Fisrt one - - , , .

- isEqual _.underscore ( JS-, http://underscorejs.org/#isEqual) , .

, .

var a = {'a' : '1', 'b' : '2', 'c' : '3'};
var b = {'a' : '1', 'b' : '2', 'c' : '3'};
_.isEqual(a, b) // --> true

, ,

var a = {'a' : '1', 'b' : '2', 'c' : '3'};
var b = {'c' : '3', 'b' : '2', 'a' : '1'}
_.isEqual(a, b) // --> also true
+6
function array_compare(a, b)
{
    // if lengths are different, arrays aren't equal
    if(a.length != b.length)
       return false;

    for(i = 0; i < a.length; i++)
       if(a[i] != b[i])
          return false;

    return true;
}
+5

, () , join:

a.join() == b.join()

, , .

+5

(a==b) , .

Underscore.js .

+2

.

// this is one way of doing it, and there are caveats about using instanceOf. 
// Its just one example, and presumes primitive types.
function areArrayElementsEqual(a1, a2)
{
    if (a1 instanceof Array) && (a2 instanceof Array)
    {
        if (a1.length!=a2.length)
            return false;
        else{
           var x;
           for (x=0;x<a1.length; x++)
              if (a1[x]!=a2[x])
                 return false;
        }
    }

    return true;

}
+1

Try using javascripts Join () to convert two arrays to strings and then compile the strings:

Join () : The string conversions of all array elements are joined into one string.

var a1 = array1.join();
var a2 = array2.join();

if(a1 == a2){
  //do something
}
0
source

This is the shortest way I've found:

""+ar1==""+ar2

Fiddle

0
source

All Articles