// THE PROBLEM:const firstArray =["cookies","milk","chocolate"]const secondArray =["cookies","milk","chocolate"]console.log(firstArray == secondArray)// always returns FALSE// THE SOLUTION:if(JSON.stringify(firstArray)===JSON.stringify(secondArray)){console.log("firstArray is the same as the secondArray")}else{console.log("firstArray is different from the secondArray")}
// Warn if overriding existing methodif(Array.prototype.equals)console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");// attach the .equals method to Array's prototype to call it on any arrayArray.prototype.equals=function(array){// if the other array is a falsy value, returnif(!array)returnfalse;// compare lengths - can save a lot of time if(this.length!= array.length)returnfalse;for(var i =0, l=this.length; i < l; i++){// Check if we have nested arraysif(this[i]instanceofArray&& array[i]instanceofArray){// recurse into the nested arraysif(!this[i].equals(array[i]))returnfalse;}elseif(this[i]!= array[i]){// Warning - two different object instances will never be equal: {x:20} != {x:20}returnfalse;}}returntrue;}// Hide method from for-in loopsObject.defineProperty(Array.prototype,"equals",{enumerable:false});