Lodash _.flatMap() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.flatMap() method creates a flattened array of values by running each element in collection through iteratee and flattening the mapped results.

Syntax:

_.flatMap(collection, iteratee)

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

  • collection: This parameter holds the collection to iterate over.
  • iteratee: This parameter holds the function invoked per iteration.

Return Value: This method returns the new flattened array.

Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.



javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
      
// Original array 
var user1 = ([35, 47, 58, 69, 94, 13, 72]);
  
// Use of _.flatMap() method
let gfg1 = _.flatMap(user1, function duplicate(n) {
  return [n, n];
})
  
// Printing the output 
console.log(gfg1);

chevron_right


Output:

[
  35, 35, 47, 47, 58, 58, 
  69, 69, 94, 94, 13, 13,
  72, 72
]

Example 2:

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring the lodash library 
const _ = require("lodash"); 
      
// Original array 
var user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]);
var user2 = ([3, 4, 5, 9, 9, 1, 7]);
  
// Use of _.flatMap() method
let gfg1 = _.flatMap(user1, function duplicate(n) {
  return [n, n];
})
  
let gfg2 = _.flatMap(user2, function duplicate(n) {
  return [n, n];
})
  
// Printing the output 
console.log(gfg1);
console.log(gfg2);

chevron_right


Output:

[
  3.5, 3.5, 4.7, 4.7, 5.8, 5.8, 
  6.9, 6.9, 9.4, 9.4, 1.3, 1.3,
  7.2, 7.2
]
[
  3, 3, 4, 4, 5, 5,
  9, 9, 9, 9, 1, 1,
  7, 7
]

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.

full-stack-img




My Personal Notes arrow_drop_up


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.