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

Conrad.Dean picture Conrad.Dean · Aug 7, 2014 · Viewed 249k times · Source

lodash lets me check for membership of basic data types with includes:

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

But the following doesn't work:

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

This confuses me because the following methods that search through a collection seem to do 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 do I check for the membership of an object in a collection with includes ?

edit: question was originally for for lodash version 2.4.1, updated for lodash 4.0.0

Answer

p.s.w.g picture p.s.w.g · Aug 7, 2014

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

({"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, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

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