Thursday, September 4, 2025
HomeLanguagesJavascriptLodash _.flatMap() Method

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




// 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);


Output:

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

Example 2:

javascript




// 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);


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.

RELATED ARTICLES

Most Popular

Dominic
32260 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS