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 when working on a project where lodash is part of the stack.
Still there is what the lodash includes methods does, and there are all the other ways of doing the same thing both with and without lodash, so I thought I would take a moment to write a post around this topic for what it is worth.
I have a test lodash Github repository where is where I have the source code examples that I am writing about here as well as with all my other posts on lodash.
The includes method can be used as a way to find if a value is in an array, as it is a collection method that can be used with any object in general including arrays. So then to start off with the lodash includes method in this section I will just be going over a few simple examples of the lodash includes method and arrays in general.
In this case I just need to call the lodash includes method and pass an the array as the first argument followed by the value that I want to test if it is included or not.
An index value can be given as the third argument to the method. This index value will be observed as a starting index value when it comes to checking the values from left to right.
When I give a negative from index value it counts as the index value from the end of the collection.
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.
Here I have an example of the _.includes method that is used to find if a string contains a given substring.
One issue of concern is that it is a late method, so it will not work in older clients without a polyfill. If you do care a great deal about supporting older clients it is not just a matter of using lodash though also. However getting into that would be off topic.
When just comparing a given value to all values in an array that is one thing. However in other cases I might need to do some more complex expression for each element in an array, and when it comes to that the array some method gives me that greater flexibility when it comes to having control over what is used to find if an array includes something.
When it comes to using a native array method with an object that is not an array then I just need to convert that object to an array, or use one of the function prototype methods in the event of an array like object. For this example I am using the Object.values static method which is similar to the Object.keys method only it will return an array of values rather than the key names of an object. Then once I have my array of values I can of course use the native array includes or some method as a way to test for the presence of a value in the resulting array.
When it comes to checking for a simple static sub string value in a string there is just using the index of method of the string prototype.