Last active
March 12, 2023 02:02
-
-
Save nhatnx/3968895014876736ce1f020b8b0d8110 to your computer and use it in GitHub Desktop.
Compare 2 objects recursively (if don't want to use lowdash _isEqual)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://gomakethings.com/check-if-two-arrays-or-objects-are-equal-with-javascript/ | |
var isEqual = function (value, other) { | |
// Get the value type | |
var type = Object.prototype.toString.call(value); | |
// If the two objects are not the same type, return false | |
if (type !== Object.prototype.toString.call(other)) return false; | |
// If items are not an object or array, return false | |
if (['[object Array]', '[object Object]'].indexOf(type) < 0) return false; | |
// Compare the length of the length of the two items | |
var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length; | |
var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length; | |
if (valueLen !== otherLen) return false; | |
// Compare two items | |
var compare = function (item1, item2) { | |
// Get the object type | |
var itemType = Object.prototype.toString.call(item1); | |
// If an object or array, compare recursively | |
if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) { | |
if (!isEqual(item1, item2)) return false; | |
} | |
// Otherwise, do a simple comparison | |
else { | |
// If the two items are not the same type, return false | |
if (itemType !== Object.prototype.toString.call(item2)) return false; | |
// Else if it's a function, convert to a string and compare | |
// Otherwise, just compare | |
if (itemType === '[object Function]') { | |
if (item1.toString() !== item2.toString()) return false; | |
} else { | |
if (item1 !== item2) return false; | |
} | |
} | |
}; | |
// Compare properties | |
if (type === '[object Array]') { | |
for (var i = 0; i < valueLen; i++) { | |
if (compare(value[i], other[i]) === false) return false; | |
} | |
} else { | |
for (var key in value) { | |
if (value.hasOwnProperty(key)) { | |
if (compare(value[key], other[key]) === false) return false; | |
} | |
} | |
} | |
// If nothing failed, return true | |
return true; | |
}; | |
/** Usage **/ | |
var arr1 = [1, 2, 3, 4, 5]; | |
var arr2 = [1, 2, 3, 4, 5]; | |
isEqual(arr1, arr2); // returns true | |
var arrObj1 = [1, 2, { | |
a: 1, | |
b: 2, | |
c: 3 | |
}, 4, 5]; | |
var arrObj2 = [1, 2, { | |
c: 3, | |
b: 2, | |
a: 1 | |
}, 4, 5]; | |
isEqual(arrObj1, arrObj2); // returns true | |
var arr1 = [1, 2, 3, 4, 5]; | |
var arr3 = [5, 4, 3, 2, 1]; | |
isEqual(arr1, arr3); // returns false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment