Lodash _.tap() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.

The _.tap() method of Sequence in lodash is used to call interceptor. Moreover, the main task of the method is to “tap into” a method chain sequence so that the intermediate results can be modified.

Syntax:

_.tap(value, interceptor)

Parameters: This method accepts two parameters as mentioned above and described below:

  • value: It is the value to be given to the interceptor.
  • interceptor: It is the function to be called.

Return Value: This method returns the value.



Example 1:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring lodash library
const _ = require('lodash');
  
// Calling tap() method
let result = _([5, 6, 7]).tap(function(arr) {
  
   // Modifying input array using push
   // operation
   arr.push(8);
 })
.value();
  
 // Displays output
 console.log(result);

chevron_right


Output:

[ 5, 6, 7, 8 ]

Example 2:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring lodash library
const _ = require('lodash');
  
// Calling tap() method
let result = _(['Geeks', 'for']).tap(function(arr) {
  
   // Modifying input array using push
   // operation
   arr.push('Geeks');
   })
   .value();
  
 // Displays output
 console.log(result);

chevron_right


Output:

[ 'Geeks', 'for', 'Geeks' ]

Example 3: Using pop operation and tail method.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring lodash library
const _ = require('lodash');
  
// Calling tap() method
let result = _(['f', 'g', 'h']).tap(function(arr) {
  
   // Modifying input array using pop
   // operation
   arr.pop();
 })
   .tail()     // Using tail() method
   .value();
  
 // Displays output
 console.log(result);

chevron_right


Output:

[ 'g' ]

Reference: https://lodash.com/docs/4.17.15#tap

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.