There are two arrays in JavaScript, they are both in the following format:
[{'drink':['alcohol', 'soft', 'hot']}, {'fruit':['apple', 'pear']}];
I need to detect if the two arrays are equal or not. they are considered equal if they contain the same elements in a different order. How can I make that?
You can try this
JSON.stringify(array1)===JSON.stringify(array2);
if you want the order also to be identical in both the arrays.With Javascript, you can't check if arrays are equals, but you can compare them like this:
The
sort
put all elements in the same order, and if both<
and>
comparisons are false it means both are the same.Does this answer your question? How to check if two arrays are equal with JavaScript?
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD
Have a look here, the second example is a function that does exactly that.
A similar function that does the same thing can be found at the bottom of this page.
http://zeeohemgee.blogspot.com/2006/07/comparing-and-copying-arrays-in.html
Hope this helps
Cheers
If
1
and2
are both the same, your array is equal.Function to compare objects/arrays:
Looping through true arrays can be achieved through
for(var i=0; i<array.length; i++)
.Walking through the properties of such an object can be done by
for(var i in object)
.If you don't understand the function, feel free to request an explanation at the comments.