HOME > lodash

[Lodash] thru() Method information and examples

Last Modified : 2023-02-28 / Created : 2023-02-28
View Count
Let's learn about the thru() method, which is one of the methods in Lodash.

# Understanding Lodash thru() Method
The Lodash thru() method is used to perform or verify something specific in the middle of a continuous chain, using the dictionary meaning of the English word "through" or "to pass through" or "to continue."

The syntax is as follows:


Although you can implement a specific function without using thru(), using it to perform an action, verify, or compare something in between the defined functions can be effective.

When executing thru(), you can receive the result of the upper chain as an argument through the internal function. You can then create and perform the desired function using this value and return it to the next chain.

! Examples of lodash thru()
Let's look at a simple example. Suppose we want to obtain the square of a series of consecutive numbers and remove values greater than 100. We can use thru() to filter the values, as shown below:
_.chain([3, 6, 9, 12, 15])
.map(n => Math.pow(n, 2))
.thru(myArray => myArray .filter(num => num < 100))

// Result
 [9, 36, 81]

As shown in the above example, using _.thru() in the middle to filter the values and obtain only values less than 100 is possible. Using thru() instead of using it independently can show how each function works in the overall process and different functional units.

! Conclusion
The Lodash thru() method is very similar to the tap() method, and both can be used for debugging or verification purposes. However, tap() does not modify the value after the function, while thru() does. Therefore, depending on the situation, you can choose to apply the appropriate method.

Another advantage of using thru() is that you can perform subsequent operations with the returned value in the middle, which can reduce the number of iterations used for filtering arrays, resulting in improved performance. For this reason, thru() can be considered a method that goes well with functional programming.

To summarize the advantages of thru(), they are as follows:

  • Convenience and performance benefits when inspecting or modifying results during work
  • Convenient for debugging or verification processes
  • Useful for passing the obtained results to the next process in the middle

We have learned about Lodash's thru() method up to this point.


Post thumbnail Merge with unique values using lodash union method


[lodash] take method, determining the length of an array Post thumbnail