Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_.isEqual reporting a difference when there is none

Tags:

lodash

I am trying to compare two objects using the .isEqual method from lodash-node package. Even though the objects are same, .isEqual returns false.

var _ = require('lodash-node');

var obj1 = {"properties":{"property":[{"comfort":["2.4 GHz"]},{"name":["Mosaic"]}]}};
var obj2 = {"properties":{"property":[{"name":["Mosaic"]},{"comfort":["2.4 GHz"]}]}};

if(_.isEqual(obj1, obj2)) //--> Returns false
    console.log('same')
else
    console.log('not same');

node:- v0.12.7
lodash-node:- v3.10.1

The objects look similar to me. Please help in pointing out if there is any difference.

like image 915
Smruti Mandal Avatar asked Sep 11 '15 06:09

Smruti Mandal


People also ask

What is _ isEqual?

_. isEqual(object1, object2); It accepts two objects as parameters and scrutinizes whether they are equal or not.

How does Lodash isEqual work?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.

Does Lodash isEqual care about order?

isEqual does not respect the order of Arrays contained within Sets · Issue #3640 · lodash/lodash · GitHub.

How do you compare objects in Lodash?

In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.


3 Answers

I realise this doesn't apply in your example but I found another case where lodash returns not equal for objects where JSON.stringify returns the same string.

In my case, one object had a property with the value undefined whereas the other object did not have that property at all.

Personally, I'd argue lodash is incorrect in this case but it's a bit subjective.

like image 90
Andy Avatar answered Oct 03 '22 06:10

Andy


The objects are not equal since even when deep-comparing, an array is an ordered collection, and order matters. Your array holds the same values, but not at the same order.

like image 20
Amit Avatar answered Oct 03 '22 07:10

Amit


The order in an array matters, so

_.isEqual([1,2], [2, 1]) === false

which is why your example returns false.

like image 41
Daniel Perez Avatar answered Oct 03 '22 07:10

Daniel Perez