Skip to content

Instantly share code, notes, and snippets.

@rahulsivalenka
Last active August 29, 2017 05:39
Show Gist options
  • Save rahulsivalenka/ba52cd1c401ad80d35a699e09d2c0c16 to your computer and use it in GitHub Desktop.
Save rahulsivalenka/ba52cd1c401ad80d35a699e09d2c0c16 to your computer and use it in GitHub Desktop.
Functions which can be used to deep compare two objects or two arrays
let src = [{
a: 25,
b: 15
}, {
a: 10,
b: [10,15],
c: [{
x: 15,
y: 10
}],
}, {
a: 25,
b: 15
}];
let mod = [{
b: [10, 15],
c: [{
x: 15,
y: 10
}],
a: 10
}, {
b: 15,
a: 25
}];
let isEqDeep = (s, m, ignoreOrder) => {
console.log('in isEqDeep', JSON.stringify(s), JSON.stringify(m));
let typeOfMod = typeof m;
let typeOfSrc = typeof s;
if (typeOfMod === typeOfSrc) {
if (typeOfMod === 'object') {
if (Array.isArray(m)) {
if (Array.isArray(s)) {
return isEqDeepArray(s, m, ignoreOrder);
} else {
return false;
}
} else {
let isEqual = true;
for (let key in m) {
let mm = m[key];
let ss = s[key];
isEqual = isEqDeep(ss, mm, ignoreOrder);
if(!isEqual) break;
}
return isEqual;
}
} else {
// not an object
return s === m;
}
} else {
return false;
}
}
let isEqDeepArray = (srcArr, modArr, ignoreOrder) => {
if(srcArr.length !== modArr.length)
return false;
return modArr.every((m, i) => {
if(ignoreOrder) {
return srcArr.some(s => {
return isEqDeep(s, m, ignoreOrder);
});
}
let s = srcArr[i];
let eq = isEqDeep(s, m);
console.log('final eq at ' + i, JSON.stringify(m), JSON.stringify(s), eq);
return eq;
});
};
// console.log('isEqDeepArray', isEqDeepArray(src, mod));
console.log('isEqDeep', isEqDeep(src, mod));
// console.log('isEqDeep', isEqDeep(src, mod, true));
// console.log('isEqDeepArray', isEqDeepArray(src, mod, true));
// console.log('isEqDeepArray', isEqDeep({ x: 10}, {x: 10, y: 15}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment