Skip to content

Instantly share code, notes, and snippets.

@magician11
Last active August 29, 2015 14:18
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 magician11/d0c979037a69555b2aa4 to your computer and use it in GitHub Desktop.
Save magician11/d0c979037a69555b2aa4 to your computer and use it in GitHub Desktop.
An implementation of deep comparison between objects
function deepEqual(val1, val2) {
if(val1 === val2) {
console.log(val1 + ' is the same as ' + val2);
return true;
} else if(typeof val1 === 'object' && typeof val2 === 'object'
&& val1 !== null && val2 !== null) {
var val1Keys = Object.keys(val1);
var val2Keys = Object.keys(val2);
var arr1Length = val1Keys.length;
if(arr1Length === val2Keys.length) {
for(var i = 0; i < arr1Length; i++) {
console.log('Looking at key ' + val1Keys[i]);
if(val1Keys[i] === val2Keys[i]) {
console.log('Checking whether ' + val1[val1Keys[i]] +
' is the same as ' + val2[val2Keys[i]]);
if(!deepEqual(val1[val1Keys[i]], val2[val2Keys[i]])) {
return false;
}
} else {
// not the same value for the current key
return false;
}
}
} else {
// not the same length of keys
return false;
}
return true;
} else {
// they're either not objects or null
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment