I am trying to compare two array of objects. Below is my code.
var result = identical([
{"depid": "100", "depname": ""},
{"city": "abc", "state": "xyz"},
{"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}}
], [
{"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}},
{"depid": "100", "depname": ""},
{"city": "abc", "state": "xyz"}
]);
console.log(result); // returns false
function identical(a, b) {
function sort(object) {
if (typeof object !== "object" || object === null) {
return object;
}
return Object.keys(object).sort().map(function (key) {
return {
key: key,
value: sort(object[key])
};
});
}
return JSON.stringify(sort(a)) === JSON.stringify(sort(b));
};
I want to know why I am getting result as false while comparing the above two array of objects.
If I pass the below object, the result is true
var result = identical([
{"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}},
{"depid": "100", "depname": ""},
{"city": "abc", "state": "xyz"}
], [
{"firstName": "John", "lastName": "Doe", "contactno": {"ph": 12345, "mob": 485428428}},
{"depid": "100", "depname": ""},
{"city": "abc", "state": "xyz"}
]);
How to compare based on keys alone and without seeing the order of objects ?