What is Lodash?
This method is used to wrap the value which we get from the method chain sequence, and it returns the exact wrapped value of a method chain.
Concept of Method chaining
If we want to perform more than one operation one after another, and the input of one operation depends upon the output of the previous operation, then we use the concept of method chaining provided by the Lodash library.
Method chaining means calling many functions one after another on an object. So that code flow looks like a sentence, and it is sometimes also called method cascading.
Method chaining was developed to avoid the confusion and complexity created by the nested method. If we want to perform multiple functions on an object or array, then we can also use the nested method where one function contains another function, and it contains another, and so on.
It is the single parameter accepted by this function, and it contains the value which we want to wrap using this function.
This function will return the wrapped value of the actual value passed as a parameter.
Let's take some examples to understand this method well.
['Gopal earns 410', 'Ayush earns 2600', 'Shivani earns 2600', 'Ankit earns 3200', 'Anjali earns 3896', 'Mansi earns 5000']
Now, we want to print the statements for each index according to the ascending order of the income. So, we used the _.chain() method on our object friend, and we applied the first sortBy() method to sort them according to their income. Then we used the .map function to iterate the object, and for each value, we printed some statements, and at last, we applied the .value() function.
So because of applying multiple functions on an object, we used the _.chain() method.
['Ayush is 21 year old', 'Shivani is 21 year old', 'Mansi is 22 year old', 'Ankit is 23 year old', 'Gopal is 24 year old']
We applied the _.chain() method on the object and used the sortBy() method to sort them according to their ages in ascending order. Now we applied the .map() function to get each value of the object and created some statements for each value. Then we used the .tail() method, which will remove the first element of the array and return the remaining value. So after removing the first element, we applied the .value() function and assigned the resultant array into a variable.
Now using console.log(), we printed the resultant array. We can clearly see that 'Anjali' has the least age, so it was the first element in the sorted array, but we removed it using the tail() method.
The reason we used the ._chain() method is that we applied multiple functions on the object like:
sortBy() method, map() method ,tail() method and value() method.
Next TopicUnderscore.js _.filter Function