Skip to content

Instantly share code, notes, and snippets.

@magician11 magician11/deepEqual.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.