Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@harmstyler
Last active December 30, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harmstyler/7896595 to your computer and use it in GitHub Desktop.
Save harmstyler/7896595 to your computer and use it in GitHub Desktop.
Compares two arrays and returns boolean value. Coffeescript and Javascript versions provided
Array::equals = (array) ->
return false unless array
return false unless @length is array.length
i = 0
while i < @length
if this[i] instanceof Array and array[i] instanceof Array
# Check and recurse into the nested arrays
return false unless this[i].equals(array[i])
else if this[i] instanceof Object and array[i] instanceof Object
# Stringify objects for comparison
return false unless JSON.stringify(this[i]) is JSON.stringify(array[i])
else return false unless this[i] is array[i]
i++
true
Array.prototype.equals = function(array) {
var i;
if (!array) {
return false;
}
if (this.length !== array.length) {
return false;
}
i = 0;
while (i < this.length) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].compare(equals[i])) {
return false;
}
} else if (this[i] instanceof Object && array[i] instanceof Object) {
if (JSON.stringify(this[i]) !== JSON.stringify(array[i])) {
return false;
}
} else {
if (this[i] !== array[i]) {
return false;
}
}
i++;
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment