Open In App

Lodash _.flatMap() Method

Last Updated : 27 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.flatMap() method creates a flattened array of values by running each element in the collection through iteratee and flattening the mapped results.

Syntax:

_.flatMap(collection, iteratee);

Parameters:

  • 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: In this example, we are passing a duplicate function to the lodash _.flatMap() method and an array and getting the result in the console.

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let 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);


Output:

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

Example 2: In this example, we are passing a duplicate function to the lodash _.flatMap() method and an array and getting the result in the console.

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let user1 = ([3.5, 4.7, 5.8, 6.9, 9.4, 1.3, 7.2]);
let 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);


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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads