Skip to content

Instantly share code, notes, and snippets.

@peinearydevelopment
Last active October 29, 2018 15:19
Show Gist options
  • Save peinearydevelopment/e2cffc9f0254c7a510a03b2bfecd302d to your computer and use it in GitHub Desktop.
Save peinearydevelopment/e2cffc9f0254c7a510a03b2bfecd302d to your computer and use it in GitHub Desktop.
/*
Request:
I need to compare 2 json objects for equality.
Ordering of keys doesn't matter(as per spec of json).
Also arrays within the objects, order doesn't matter(not per the spec).
Arrays can be nested within sub-objects and objects can be nested within arrays.
Example objects should be equal
*/
const object1 = {
a:'fred',
b: {
g: 1,
c: 'frank'
},
c: [
'q',
'f',
{
jack: 'jill',
x: 75
},
{
l: 1,
foo: 'bar'
}
],
p: 55
};
const object2 = {
p:55,
b: {
g: 1,
c: 'frank'
},
c: [
'f',
'q',
{
l: 1,
foo: 'bar'
},
{
x:75,
jack: 'jill'
}
],
a:'fred'
}
function objectsAreEqual(obj1, obj2) {
const keys1 = Object.keys(obj1).sort((k1, k2) => k1.localeCompare(k2));
const keys2 = Object.keys(obj2).sort((k1, k2) => k1.localeCompare(k2));
if (keys1.length !== keys2.length) {
return false;
}
for(let i = 0, l = keys2.length; i < l; i++) {
const key1 = keys1[i];
const key2 = keys2[i];
const val1 = obj1[key1];
const val2 = obj2[key2];
if (key1 !== key2 || typeof val1 !== typeof val2) {
return false;
}
if (val1 instanceof Object && val2 instanceof Object) {
if (Array.isArray(val1) && Array.isArray(val2)) {
if (!arraysAreEqual(val1, val2)) {
return false;
}
} else if (Array.isArray(val1) || Array.isArray(val2)) {
return false;
} else if (!objectsAreEqual(val1, val2)) {
return false;
}
} else if (val1 !== val2) {
return false;
}
}
return true;
}
function arraysAreEqual(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
arr1 = arr1.sort();
arr2 = arr2.sort();
const objs1 = [];
const objs2 = [];
for (var i = 0, l = arr1.length; i < l; i++) {
const val1 = arr1[i];
const val2 = arr2[i];
if (typeof val1 !== typeof val2){
return false;
}
if (val1 instanceof Object && val2 instanceof Object) {
if (Array.isArray(val1) && Array.isArray(val2)) {
if (!arraysAreEqual(val1, val2)) {
return false;
}
} else if (Array.isArray(val1) || Array.isArray(val2)) {
return false;
} else {
objs1.push(val1);
objs2.push(val2);
}
} else if (val1 !== val2) {
return false;
}
}
if (objs1.length !== objs2.length) {
return false;
} else {
return !!objs1.find(o1 => objs2.find(o2 => objectsAreEqual(o1, o2) !== -1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment