6

I have two arrays say a = [1,2,3] and b=[1,2,3]

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

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

3
  • 1
    You have to write the code to loop through all the elements. Commented Sep 13, 2012 at 18:19
  • @Pointy usually i do that. but just wanted to know is there any way other than looping? Commented Sep 13, 2012 at 18:20
  • 1
    No, there is no built-in array comparison facility in JavaScript. Commented Sep 13, 2012 at 18:20

8 Answers 8

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

1 Comment

array_compare([1,2,3,{a:1,b:2}],[1,2,3,{a:1,b:2}]) returns false though, so I suppose this is only usable with arrays containing primitive values.
6

You have 2 options.

Fisrt one is to use some kind of function made by yourself that will iterate over each key from both arrays and compare them.

Second option is to use isEqual from _.underscore (a really nice JS library, http://underscorejs.org/#isEqual ) This will work for both arrays and objects.

I'd use the second one as it's easier.

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

Note that order doesn't matter in objects, so you could have

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

Comments

6

If you know what (not) to expect in your array you could use join:

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

I know, this is far from bulletproof, but it can be usable some cases (when you know the order in both arrays will be the same).

4 Comments

But what about this? ["a,b"].join() == ["a","b"].join()
Then you need a custom separator. I know, using join is not bulletproof but it will work fine I you more or less know what (not) to expect in your array.
A separator also doesn't work in all cases; e.g. ["a", "b"].join("||") == ["a||b"].join("||")
True, this will only work in some cases (see previous comment). I've updated the answer to underline that.
2

If you want to compare 2 arrays, you could use JSON.stringify

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

It will also compare [nested] Objects within the array, or [nested] Arrays within 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've played a bit with the idea

7 Comments

seems like answer i am looking for, but if i have objects inside the array will it return true?
Yes, if the objects are equal: JSON.stringify([1,2,3,{a:1,b:2}]) === JSON.stringify([1,2,3,{a:1,b:2}]); returns true
This won't work if objects contain equal pairs of key:value but in different order. You can't compare objects converting them to string. That's asking for trouble.
@alexandernst: it depends on how you want to use it. It won't work for differently sorted arrays with equal values either. In such cases, sorting the arrays/object[-keys] before comparing could be an option. There are no complete or native javascript solutions, the JSON idea is one that's fairly usable imo.
Comparing objects by converting them to a string isn't a good idea in any language, nor a good option for anything. Don't try to compare lemons with apples by painting the lemons in red.
|
2

(a==b) is doing a reference comparaison not a content comparaison.

Underscore.js brings some feature for that.

1 Comment

is there any way to compare two arrays?
1

You must write code to compare each element of an array to accomplish your objective.

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

}

Comments

1

Try using javascripts Join() method to convert the two arrays to strings and then compage 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
}

Comments

0

It's the shortest way I found:

""+ar1==""+ar2

Fiddle

1 Comment

This returns a false positive if the objects inside the array aren't equal. E.g.: jsfiddle.net/Pmt4q/5

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.