How to determine array equality in JavaScript?

JavaScript has two arrays, both in the following format:

[{'drink':['alcohol', 'soft', 'hot']}, {'fruit':['apple', 'pear']}]; 

I need to determine if two arrays are equal or not. they are considered equal if they contain the same elements in a different order. How can i do this?

+8
javascript string equality arrays
source share
5 answers
  • Check the length of both arrays
  • Scroll through the first array, compare each variable with the second array.

If 1 and 2 match, your array is equal.

Function for comparing objects / arrays:

Quoting through true arrays can be achieved via for(var i=0; i<array.length; i++) .
Passing the properties of such an object can be done using for(var i in object) .

 function recursiveCompare(obj, reference){ if(obj === reference) return true; if(obj.constructor !== reference.constructor) return false; if(obj instanceof Array){ if(obj.length !== reference.length) return false; for(var i=0, len=obj.length; i<len; i++){ if(typeof obj[i] == "object" && typeof reference[j] == "object"){ if(!recursiveCompare(obj[i], reference[i])) return false; } else if(obj[i] !== reference[i]) return false; } } else { var objListCounter = 0; var refListCounter = 0; for(var i in obj){ objListCounter++; if(typeof obj[i] == "object" && typeof reference[i] == "object"){ if(!recursiveCompare(obj[i], reference[i])) return false; } else if(obj[i] !== reference[i]) return false; } for(var i in reference) refListCounter++; if(objListCounter !== refListCounter) return false; } return true; //Every object and array is equal } 

If you do not understand this feature, feel free to request an explanation in the comments.

+6
source share

Does this answer your question? How to check if two arrays are equal with JavaScript?

 var equal = array1.compareArrays(array2); 
+2
source share

http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD

Look here, the second example is a function that does just that.

A similar function that does the same can be found at the bottom of this page.

http://zeeohemgee.blogspot.com/2006/07/comparing-and-copying-arrays-in.html

Hope this helps

Greetings

+1
source share

You can try this JSON.stringify(array1)===JSON.stringify(array2); if you want the order also to be identical in both arrays.

0
source share

With Javascript, you cannot check if arrays are equal, but you can compare them as follows:

 var arr1 = ['alcohol', 'soft', 'hot'], arr2 = ['apple', 'pear'], arr3 = ['soft', 'hot', 'alcohol']; function isSame(a1, a2){ return !(a1.sort() > a2.sort() || a1.sort() < a2.sort()); } console.log( isSame(arr1, arr2) ); //false console.log( isSame(arr1, arr3) ); //true 

sort put all the elements in the same order, and if both comparisons < and > are false, it means that both of them are the same.

0
source share

All Articles