How to use the flatMap function from lodash

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

lodash.flatMap is a function provided by the Lodash library that flattens and maps an array of values into a new array.

441
442
443
444
445
446
447
448
449
450
if (!Array.isArray(nativeDependencies) || nativeDependencies.length === 0) {
    return false;
}
const dependencies = JSON.parse(spawn.sync('npm', ['ls', '--json', '--prod']).stdout.toString());
const jsonProperties = Object.keys(flat.flatten(dependencies));
nativeDependencies = _.flatMap(nativeDependencies, (item) =>
    path.dirname(item.substring(item.indexOf('node_modules') + 'node_modules'.length)).split(path.sep)
)
    .filter((item) => item.length > 0)
    .filter((item) => !item.includes('zeromq') && !item.includes('canvas') && !item.includes('keytar')) // Known native modules
fork icon209
star icon960
watch icon43

+ 2 other calls in file

122
123
124
125
126
127
128
129
130
131
132


Album.prototype.pickPreviews = function (options) {
  // consider nested albums if there aren't enough photos
  let potential = this.files
  if (potential.length < PREVIEW_COUNT) {
    const nested = _.flatMap(this.albums, 'previews').filter(file => file !== PREVIEW_MISSING)
    potential = potential.concat(nested)
  }
  // choose the previews
  if (!options.albumPreviews || options.albumPreviews === 'first') {
fork icon80
star icon649
watch icon21

+ 4 other calls in file

How does lodash.flatMap work?

lodash.flatMap is a function provided by the Lodash library that flattens and maps an array of values into a new array. When you call lodash.flatMap, you pass in two arguments: the array to be processed and a function that maps each element of the array to a new array. The function should return an array of values for each element of the original array. The lodash.flatMap function then iterates over each element of the input array and applies the mapping function to each element. The resulting arrays are then flattened into a single array, and returned as the result. By default, lodash.flatMap uses a depth of 1 when flattening the resulting array. This means that any arrays returned by the mapping function are flattened by a single level, but any nested arrays within them are left intact. You can change the depth of flattening by passing a second argument to the function. Overall, lodash.flatMap is a convenient way to apply a mapping function to each element of an array and flatten the resulting arrays into a single array. This can be useful for tasks like transforming or filtering data in an array.

12
13
14
15
16
17
18
19
20
21

if (!duplicateIds.length) {
  return;
}

let invalidItems = _.flatMap(duplicateIds, id => _.filter(items, { id }));
return ['Duplicate IDs found:']
  .concat(
    invalidItems.map(
      ({ id, relativePath }) => `ID: "${id}" Relative Path: ${relativePath}`
fork icon67
star icon252
watch icon0

37
38
39
40
41
42
43
44
45
46
const removeUndefinedValues = (obj) => _.pickBy(obj, isDefined);
const removeNullValues = (obj) => _.pickBy(obj, isNotNull);
const removeUndefinedAndNullValues = (obj) => _.pickBy(obj, isDefinedAndNotNull);
const removeUndefinedAndNullAndEmptyValues = (obj) => _.pickBy(obj, isDefinedAndNotNullAndNotEmpty);
const isBlank = (value) => _.isEmpty(_.toString(value));
const flattenMap = (collection) => _.flatMap(collection, (x) => x);
// ========================================================================
// GENERIC UTLITY
// ========================================================================

fork icon74
star icon51
watch icon20

+ 15 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const _ = require("lodash");

const data = [
  { id: 1, values: [1, 2, 3] },
  { id: 2, values: [4, 5] },
  { id: 3, values: [6, 7, 8] },
];

const result = _.flatMap(data, (item) =>
  item.values.map((value) => ({ id: item.id, value }))
);

console.log(result);
// Output: [
//   { id: 1, value: 1 },
//   { id: 1, value: 2 },
//   { id: 1, value: 3 },
//   { id: 2, value: 4 },
//   { id: 2, value: 5 },
//   { id: 3, value: 6 },
//   { id: 3, value: 7 },
//   { id: 3, value: 8 }
// ]

In this example, we start with an array of objects data, where each object contains an id property and an array of values. We then call lodash.flatMap on this array, passing in a function that maps each object to an array of { id, value } pairs. The mapping function first calls the map method on the values array of each object, which returns an array of { id, value } pairs. These pairs are then flattened into a single array using lodash.flatMap, and returned as the result. The resulting array contains all { id, value } pairs from each object in the original data array, flattened into a single array.

122
123
124
125
126
127
128
129
130
131
module.exports.findLastIndex       = _.findLastIndex;
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;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

414
415
416
417
418
419
420
421
422
423
  const lodashCallback = (x) => [x, x]
  const ramdaCallback = (x) => [x, x]
  const nativeCallback = (x) => [x, x]
  return {
    iiris: () => A.flatMap(iirisCallback, array),
    lodash: () => _.flatMap(array, lodashCallback),
    ramda: () => R.chain(ramdaCallback, array),
    native: () => array.flatMap(nativeCallback),
  }
},
fork icon1
star icon31
watch icon0

609
610
611
612
613
614
615
616
617
liquid.filters.isAboutItem = (menuArray, path) => {
  const outreachPattern = new RegExp('outreach');
  if (outreachPattern.test(path)) {
    return false;
  }
  const paths = _.flatMap(menuArray, getPath);
  const inMenu = _.indexOf(paths, path);
  return inMenu !== -1;
};
fork icon7
star icon15
watch icon0

139
140
141
142
143
144
145
146
147
148
const studyRightEducation = getEducation(studyright.education_id)

const personsTermRegistrations = allTermRegistrations.filter(
  registration => registration.study_right_id === studyright.id
)
const termRegistrations = flatMap(personsTermRegistrations, 'term_registrations')

if (!studyRightEducation) return acc

if (isBaMa(studyRightEducation)) {
fork icon3
star icon12
watch icon0

151
152
153
154
155
156
157
158
159
 * Get the licence numbers for this invoice by inspecting
 * the Licence objects associated with each InvoiceLicence
 * object associated with this invoice
 */
getLicenceNumbers () {
  return flatMap(this.invoiceLicences, invoiceLicence => {
    return invoiceLicence.licence.licenceNumber
  })
}
fork icon2
star icon4
watch icon8

74
75
76
77
78
79
80
81
82
83
84
85
    }
  }
}


let perms = _.permutations([0, 1, 2, 3], 4).map((L) =>
  _.flatMap(L.map((e) => [2 * e + 1, 2 * e]))
);


// perms = [[3, 5, 2, 4, 1, 0, 7, 6]];

fork icon1
star icon4
watch icon0

220
221
222
223
224
225
226
227
228
229
230
231
232
console.log(find); // => 4


const findLast = _.findLast([4, 5, 6], n => n % 2 == 0);
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]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

49
50
51
52
53
54
55
56
57
58
---

Calculate all possible permutations of all possible sizes.

```javascript
let permutations = _.flatMap([2, 4, 6], (v, i, a) => _.permutations(a, i + 1));
// => [[2], [4], [6], [2, 4], [2, 6], [4, 2], [4, 6], [6, 2], [6, 4], [2, 4, 6], [2, 6, 4], [4, 2, 6], [4, 6, 2], [6, 2, 4], [6, 4, 2]]
```

---
fork icon0
star icon4
watch icon2

+ 3 other calls in file

177
178
179
180
181
182
183
184
185
186
187
188
189


    res.json(format.list(remediations, count.length, limit, offset, req.query.sort, req.query.system));
});


async function resolveSystems (remediation) {
    const systems = _.flatMap(remediation.issues, 'systems');
    const ids = _(systems).map('system_id').uniq().value();


    const resolvedSystems = await inventory.getSystemDetailsBatch(ids);

fork icon17
star icon1
watch icon8

+ 4 other calls in file

64
65
66
67
68
69
70
71
72
73
*   season : 'fall'
* }];
*
* // take the ids from the JSON array
* var filter = take('id');
* var ids = _.flatMap(array, filter); // returns [1, 2, 3];
* var ids = _.map(array, filter); // returns [ [1], [2], [3]];
*
* // take both the id and the season properties from the array
* var filter = take('id', 'season');
fork icon2
star icon0
watch icon0

6
7
8
9
10
11
12
13
14
15
16
describe('util.js', () => {
  it('#take() should take values from one key of each object in an array of objects', () => {
    const objects = [{ id : 1 }, { id : 2 }, { id : 3 }];
    const expected = [1, 2, 3];
    const filter = util.take('id');
    const ids = _.flatMap(objects, filter);
    expect(ids).to.deep.equal(expected);
  });


  it('#requireModuleIfExists() should require module if it exists', () => {
fork icon2
star icon0
watch icon0

304
305
306
307
308
309
310
311
312
313
      func,
    };
  },
);

this.entryFunctions = _.flatMap(entries, (value, key) => {
  const entry = path.relative('.', value);
  const entryFile = _.replace(
    entry,
    new RegExp(`${path.extname(entry)}$`),
fork icon0
star icon1
watch icon0

112
113
114
115
116
117
118
119
120
121
122
123
124


const getMostRecentVersion = () => {
  const coreMigrations = getMigrations('./packages/bp/dist')
  const modules = fs.readdirSync('./modules')


  const moduleMigrations = _.flatMap(modules, module => getMigrations(`./modules/${module}/dist`))
  const versions = [...coreMigrations, ...moduleMigrations].map(x => x.version).sort(semver.compare)


  return _.last(versions)
}
fork icon0
star icon0
watch icon1

+ 5 other calls in file

98
99
100
101
102
103
104
105
106

async getRoutes() {
  const routesMap = {};

  _.forEach(strapi.api, (api, apiName) => {
    const routes = _.flatMap(api.routes, route => {
      if (_.has(route, 'routes')) {
        return route.routes;
      }
fork icon0
star icon0
watch icon1

+ 5 other calls in file

398
399
400
401
402
403
404
405
406
407
);
const buildingChars = _.transform(
  langShort === 'zh' ? _.pickBy(buildingData.chars, (v, k) => k.startsWith('char_')) : {},
  (obj, { charId, buffChar }) => {
    const shortId = charId.replace(/^char_/, '');
    obj[shortId] = _.flatMap(buffChar, ({ buffData }) =>
      buffData.map(({ buffId, cond: { phase, level } }) => ({
        id: idStandardization(buffId),
        unlock: `${phase}_${level}`,
      }))
fork icon0
star icon0
watch icon1

+ 4 other calls in file

6
7
8
9
10
11
12
13
14
15
 *  - others are parsed for types
 *  - Returns array of arguments already converted to string with type
 *  @param {*[]} commandArguments
 */
const parseArguments = commandArguments =>
  _.flatMap(_.tail(commandArguments), arg =>
    match(arg)
      .when(
        () => arg.type === 'ObjectExpression',
        () => `${arg.properties[0].key.name}: any`
fork icon0
star icon0
watch icon1

Other functions in lodash

Sorted by popularity

function icon

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