shreedhar shreedhar - 9 months ago 38
Javascript Question

comparison of array in javascript

I have two arrays say

a = [1,2,3]

if i do
it returns false. how to compare two arrays with same values?

will return true, but how can we compare two arrays instead of 2 same elements inside two different arrays?


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