Reputation: 2193
I want to make this via lodash:
first = { one: 1, two: 2, three: 3 }
second = { three: 3, one: 1 }
_.CustomisEqual(first, second);
// → true
third = { one: 1, two: 2, three: 3 }
fourth = { three: 4, one: 1 }
_.CustomisEqual(third, fourth);
// → false
But usual _.isEqual
does not support this method of comparison, is there a way to make this comparison via lodash?
Upvotes: 1
Views: 6009
Reputation: 8509
function CustomisEqual(objOne, objTwo) {
return !!_([objOne]).filter(objTwo).size();
}
first = { one: 1, two: 2, three: 3 }
second = { three: 3, one: 1 }
var resOne = CustomisEqual(first, second);
console.log('resOne ', resOne);
// → true
third = { one: 1, two: 2, three: 3 }
fourth = { three: 4, one: 1 }
var resTwo = CustomisEqual(third, fourth);
console.log('resTwo ', resTwo);
// → false
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
Upvotes: 2
Reputation: 685
I think below solution might be useful.
var first = { one: 1, two: 2, three: 3 };
var second = { three: 3, one: 1 };
var third = { one: 1, two: 2, three: 3 };
var fourth = { three: 4, one: 1 };
function customIsEquals(first,second) {
var ret = true;
_.forEach(second,function(value, key){
if(first[key]!==value){
ret = false;
}
});
return ret;
}
_.mixin({ 'customIsEquals': customIsEquals });
console.log(_.customIsEquals(first,second));
console.log(_.customIsEquals(third,fourth));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>
Upvotes: 0
Reputation: 2672
Essentially this:
// mock lodash
var _ = {}
// create custom lodash method
_.CustomisEqual = function (a, b) {
// get array of the keys in object
var aKeys = Object.keys(a)
var bKeys = Object.keys(b)
// get the array of the keys with the smallest length
var minKey = (aKeys.length > bKeys.length ? bKeys : aKeys)
// get the obejct with the smallest and greatest length
var minObj = (aKeys.length > bKeys.length ? b : a)
var maxObj = (a === minObj ? b : a)
// get the length from the smallest length array of the keys
var minLen = Math.min(aKeys.length, bKeys.length)
// iterate through the smallest object
for (var i = 0; i < minLen; i++) {
var currentKey = minKey[i]
// ignore values that are in one but not the other
if (maxObj[currentKey] !== undefined &&
// compare defined values of both objects
maxObj[currentKey] !== minObj[currentKey]) {
// return false if they don't match
return false
}
}
// otherwise, they do match, so return true
return true
}
var first = { one: 1, two: 2, three: 3 }
var second = { three: 3, one: 1 }
console.log(_.CustomisEqual(first, second)) // → true
var third = { one: 1, two: 2, three: 4 }
var fourth = { three: 3, one: 1 }
console.log(_.CustomisEqual(third, fourth)) // → false
I hope that helps!
Upvotes: 0