lodash includes method to check Strings, Arrays, and Objects for a value

Time for yet another one of my posts on lodash, today I will be writing about the _.includes method and why It might be useful in some situations.

1 - lodash includes

The _.includes method is one of the collection methods in lodash that work with Arrays, and Objects in general. In addition this method can also be used with strings. The nature of the method is one where it can be used as a means to test if a value is included in a collection.

2 - Example of _.includes With strings

Here I have an example of the _.includes method that is used to find if a string contains a given substring.

1
2
3
4
// Strings
var str = 'foo;man;chew';
console.log( _.includes(str,'man') ); // true
console.log( _.includes(str,'bar') ); // false

3 - Example of _.includes With arrays

The includes method can also be used as a way to find if a value is in an array as well.

1
2
3
4
5
// Arrays
var arr = ['a','b','c'];
console.log( _.includes(arr,42) ); // false
console.log( _.includes(arr,'d') ); // false
console.log( _.includes(arr,'c') ); // true

4 - Example of _.includes With objects

When working with an object the method will return true if one of the object values is equal to the value given, but not with the key names.

1
2
3
4
5
// Objects
var obj = {name:'jack'};
console.log( _.includes(obj,'name') ); // false
console.log( _.includes(obj,'jill') ); // false
console.log( _.includes(obj,'jack') ); // true

5 - Giving a from index value

An index value can be given as the third argument to the method.

1
2
console.log(_.includes(['a','b','c'],'b',1)); // true
console.log(_.includes(['a','b','c'],'b',2)); // false

6 - Negative from index values

When I give a negative from index value it counts as the index value from the end of the collection.

1
console.log(_.includes(['a','b','c'],'b',-1)); // false

7 - Conclusion

The includes method in lodash can be used as a quick way to find if a given value is in a collection in general. It is not like there are other ways of doing this in plain old javaScript by itself, but if lodash is part of the stack it is there to help with this sort of thing. If you enjoyed this post you might want to check out my main post on lodash in general.