Skip to content

Instantly share code, notes, and snippets.

@paul-em
Last active May 16, 2023 23:43
Show Gist options
  • Save paul-em/9043317a5b2076ba636454c389c4121a to your computer and use it in GitHub Desktop.
Save paul-em/9043317a5b2076ba636454c389c4121a to your computer and use it in GitHub Desktop.
deep equals method for comparing variables including objects
/**
*
* This will deep check two variables including objects
* It works in IE9+
* Note: equals(NaN, NaN) uses js default behaviour: false
*
* equals(1, 1) --> true
* equals(1, 2) --> false
*
* equals({a: 1}, {a: 1}) --> true
* equals({a: 1}, {a: 2}) --> false
*
* equals({a: [{b: 2}]}, {a: [{b: 2}]}) --> true
* equals({a: [{b: 2}]}, {a: [{b: 3}]}) --> false
*
* equals(new Date(1), new Date(1)) --> true
* equals(new Date(1), new Date(2)) --> false
*
* @param o1 any value
* @param o2 any other value to compare to o1
* @returns {boolean}
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (typeof o1 !== typeof o2 || !!o1 !== !!o2) return false;
if (Array.isArray(o1) !== Array.isArray(o2)) return false;
if (Array.isArray(o1)) {
return o1.length === o2.length && !o1.some(function (o1Item, index) {
return !equals(o1Item, o2[index])
});
} else if (typeof o1 === 'object') {
if (o1 instanceof Date) return o1.getTime() === o2.getTime();
var o1Keys = Object.keys(o1);
var o2Keys = Object.keys(o2);
return o1Keys.length === o2Keys.length && !o1Keys.some(function (o1Key) {
return !equals(o1[o1Key], o2[o1Key])
});
}
return false;
}
@mostapha
Copy link

Thanks, exactly what I need

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment