How to use the flatMapDeep function from lodash

Find comprehensive JavaScript lodash.flatMapDeep code examples handpicked from public code repositorys.

lodash.flatMapDeep is a method in the Lodash library that recursively maps and flattens an array using a provided function.

123
124
125
126
127
128
129
130
131
132
module.exports.findLastKey         = _.findLastKey;
module.exports.first               = _.first;
module.exports.firstExisting       = _.firstExisting;
module.exports.fix                 = _.fix;
module.exports.flatMap             = _.flatMap;
module.exports.flatMapDeep         = _.flatMapDeep;
module.exports.flatMapDepth        = _.flatMapDepth;
module.exports.flatten             = _.flatten;
module.exports.flattenDeep         = _.flattenDeep;
module.exports.flattenDepth        = _.flattenDepth;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

223
224
225
226
227
228
229
230
231
232
233
234
235
console.log(findLast); // => 6


const flatMap = _.flatMap([1, 2], n => [n, n]);
console.log(flatMap); // => [1, 1, 2, 2]


const flatMapDeep = _.flatMapDeep([1, 2], n => [[n, n]]);
console.log(flatMapDeep); // => [1, 1, 2, 2]


const flatMapDepth = _.flatMapDepth([1, 2], (n) => [[[n, n]]], 2);
console.log(flatMapDepth); // => [1, 1, 2, 2]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

How does lodash.flatMapDeep work?

lodash.flatMapDeep is a function in the Lodash library that iterates over a collection, flattens it recursively, and maps each element using a given function. It behaves the same as lodash.flatMap, but it also flattens nested arrays recursively.

3
4
5
6
7
8
9
10
11
12
13
14
/**
 * flatMapDeep - Этот метод подобен _.flatMap, за исключением того, что он рекурсивно сглаживает сопоставленные результаты.
 */


// lodash
console.log("lod.flatMapDeep([1, 2], n => [n, n])", lod.flatMapDeep([1, 2], n => [n, n]));
console.log("lod.flatMapDeep([1, [2]], n => n)", lod.flatMapDeep([1, [2]], n => n));
console.log("lod.flatMapDeep([1, [2, [3]]], n => n)", lod.flatMapDeep([1, [2, [3]]], n => n));


// es6
fork icon0
star icon0
watch icon0

+ 8 other calls in file

-3
-2
-1
const items = [1,[2,[3,[4]]]]
const newItems = _.flatMapDeep(items);
console.log(newItems)
fork icon0
star icon0
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
const arr = [1, [2, [3, [4]], 5]];
const flattenedArr = _.flatMapDeep(arr);
console.log(flattenedArr); // [1, 2, 3, 4, 5]

In this example, lodash.flatMapDeep is used to recursively flatten a nested array arr. The resulting flattened array is assigned to the variable flattenedArr and logged to the console.

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)