Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isEqual vs isMatch - Does isMatch ignore the order to nested array elements?

Tags:

node.js

lodash

I'm using lodash for comparing below two objects:

obj1 = {
    "_id": "57767",
    "Re": {
        "PropertyTypes": [
            {
                "AllocationID": 13870,
                "Percentage": null,
                "Type": "Hotels",
                "Value": null
            },
            {
                "AllocationID": 13867,
                "Percentage": null,
                "Type": "Industrial",
                "Value": null
            }
        ]
    }
}

obj2 = {
    "_id": "57767",
    "Re": {
        "PropertyTypes": [
            {
                "AllocationID": 13867,
                "Percentage": null,
                "Type": "Industrial",
                "Value": null
            },
            {
                "AllocationID": 13870,
                "Percentage": null,
                "Type": "Hotels",
                "Value": null
            }
        ]
    }
}

I see that with isEqual(obj1, obj2), the comparison fails and with isMatch(obj1, obj2), it works fine.

I would like to know if both isEqual and isMatch work in exactly the same ways except for the fact that the order of the PropertyTypes array's elements is ignored by isMatch in this case. I did not find this info in isMatch's documentation.

like image 544
Akshay Maldhure Avatar asked Jan 28 '26 15:01

Akshay Maldhure


1 Answers

Not sure what you mean by "work in exactly the same way", however here's my understanding:

  • _.isMatch and _.isEqual share the same internal logics, _isMatch calling said underlying logics with explicit partial and unordered flags (so I guess we can say they work quite the same way)
  • I'd say that generally _isMatch is to be used to assert an input object - e.g. a configuration - is at least yet maybe not exactly well shaped beforehand, whereas _.isEqual handles the purest, strictest comparison
  • because of this validation-like behavior, there's also the concept of partial flag, which might be a pitfall given the data you show, for instance:
obj1 = {
  a: 123,
  b: 456,
  c: 789
};
obj2 = {
  a: 123,
  b: 456
}
_.isMatch(obj1, obj2); // true, `c` wasn't "asserted"
_.isMatch(obj2, obj1); // false, missing value for `c`

To extend this to an example closer to your case, and since it's a deep comparison:

obj1 = {
  PropertyTypes: [{
    id: 13867
  }, {
    id: 13870
  }]
};
obj2 = {
  PropertyTypes: [{
    id: 13867
  }, {
    id: 13870
  }, {
    id: 11111
  }]
};
_.isMatch(obj1, obj2); // false, missing 11111 value
_.isMatch(obj2, obj1); // true, even though there's one more item in the array

Hope this helps!

like image 163
Stock Overflaw Avatar answered Jan 30 '26 07:01

Stock Overflaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!