How to use the includes method in lodash to check if an object is in a collection?

lodash allows me to check for basic data types using includes :

 _.includes([1, 2, 3], 2) > true 

But the following does not work:

 _.includes([{"a": 1}, {"b": 2}], {"b": 2}) > false 

This bothers me because the following methods that look at the collection look just fine:

 _.where([{"a": 1}, {"b": 2}], {"b": 2}) > {"b": 2} _.find([{"a": 1}, {"b": 2}], {"b": 2}) > {"b": 2} 

What am I doing wrong? How to check the ownership of an object in a collection using includes ?

edit: the question was originally for lodash 2.4.1 updated for lodash 4.0.0

+65
javascript functional-programming lodash
Aug 6 '14 at
source share
1 answer

includes (previously called contains and include ) method compares objects by reference (more precisely, with === ). Since the two object literals {"b": 2} in your example represent different instances, they are not equal. Note:

 ({"b": 2} === {"b": 2}) > false 

However, this will work because there is only one instance of {"b": 2} :

 var a = {"a": 1}, b = {"b": 2}; _.includes([a, b], b); > true 

On the other hand, where (deprecated in version 4) and find compare objects by their properties, so they do not require reference equality. As an alternative to includes you can try some (also an alias like any ):

 _.some([{"a": 1}, {"b": 2}], {"b": 2}) > true 
+101
Aug 6 '14 at 10:16
source share



All Articles