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?
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?
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;
}
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.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
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).
["a,b"].join() == ["a","b"].join()["a", "b"].join("||") == ["a||b"].join("||")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
JSON.stringify([1,2,3,{a:1,b:2}]) === JSON.stringify([1,2,3,{a:1,b:2}]); returns true(a==b) is doing a reference comparaison not a content comparaison.
Underscore.js brings some feature for that.
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;
}