Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active August 29, 2015 14:01
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 jremmen/738f9d36330937a19020 to your computer and use it in GitHub Desktop.
Save jremmen/738f9d36330937a19020 to your computer and use it in GitHub Desktop.
js: object/array isEqual method
Object.prototype.isEqual = function(obj) {
function iter(a, b) {
for(p in a) {
if(a.hasOwnProperty(p)) {
if(!b.hasOwnProperty(p)) return false;
else if(['array', 'object'].indexOf(typeof b[p]) > -1) {
if(!iter(b[p], a[p])) return false;
}
else if(b[p] !== a[p]) return false;
}
}
return true;
}
return iter(obj, this) && iter(this, obj);
}
mittens = {color: 'white', age: 1, eyes: 'blue', sex: 'female', toys: ['yarn', 'catnip']}
furball = {color: 'black', age: 2, eyes: 'yellow', sex: 'male', toys: ['mice', 'lizards']}
purrster = {color: 'orange', age: 1, eyes: 'blue', sex: 'male', toys: ['boxes', 'shadows']}
blankinclaws = {color: 'brown', age: 21, eyes: 'brown', sex: 'male', toys: ['balls']}
a = {animals: [mittens, furball, purrster]}
b = {animals: [mittens, furball, purrster]}
c = {animals: [mittens, furball, purrster, blankinclaws ]}
a.isEqual(b) // true
b.isEqual(a) // true
c.isEqual(a) // false
a.isEqual(c) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment