Skip to content

Instantly share code, notes, and snippets.

@nodew
Created December 29, 2018 13:44
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 nodew/765e106dca5c1b3e9f301d31483b0c8a to your computer and use it in GitHub Desktop.
Save nodew/765e106dca5c1b3e9f301d31483b0c8a to your computer and use it in GitHub Desktop.
Test if two variables in JavaScript are deep equal
const baseTypes = [
"[object Number]",
"[object String]",
"[object Undefined]",
"[object Boolean]",
"[object Symbol]",
"[object Function]"
]
function deepEqual(a, b) {
const typeOfA = Object.prototype.toString.call(a);
const typeOfB = Object.prototype.toString.call(b);
if (typeOfA !== typeOfB) {
return false;
}
if (baseTypes.includes(typeOfA)) {
return a === b;
}
if (typeOfA === "[object Array]") {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
if (!deepEqual(a[i], b[i])) {
return false
}
}
}
if (typeOfA === "[object Object]") {
const keysOfA = Object.keys(a);
const keysOfB = Object.keys(b);
if (keysOfA.length !== keysOfB.length) {
return false;
}
for (let i = 0; i < keysOfA.length; i++) {
let key = keysOfA[i];
if (!deepEqual(a[key], b[key])) {
return false
}
}
}
return true;
}
console.log(deepEqual({a: 1, b: [1, 2]}, {a: 1, b: [1, 2, 3]}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment