How to use the flatten function from lodash

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

lodash.flatten is a function that creates a new array by flattening a nested array.

5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
*  to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
fork icon73
star icon711
watch icon29

+ 5 other calls in file

125
126
127
128
129
130
131
132
133
134
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;
module.exports.flip                = _.flip;
module.exports.flip2               = _.flip2;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.flatten work?

The lodash.flatten function creates a new array by flattening a nested array. If the array passed to the function contains any nested arrays, lodash.flatten recursively flattens them. Here's how the function works in detail: lodash.flatten takes an array as its argument. It creates a new, empty array to hold the flattened values. It loops over each element in the array. If the element is not an array, it is pushed into the new array. If the element is an array, lodash.flatten is recursively called on the nested array to flatten it. The flattened values are pushed into the new array. The new, flattened array is returned. Here's an example of using lodash.flatten to flatten a nested array: javascript Copy code {{{{{{{ const nestedArray = [1, [2, [3, [4]], 5]]; const flattenedArray = _.flatten(nestedArray); console.log(flattenedArray); // [1, 2, 3, 4, 5] In this example, the nestedArray contains three levels of nesting. lodash.flatten recursively flattens the array, creating a new, flattened array containing all the values. The flattened array is then logged to the console.

143
144
145
146
147
148
149
150
151
152
}
else if ( cursor.isInstanceOf(Array) ) {
    var cursorsArray = cursor.list().map(function(asyncValueCursor) {
        return getAsyncValueCursors(asyncValueCursor);
    });
    return _.flatten(cursorsArray);
}
else {
    throw new Error("getPathAsyncValueListCursors can only be called on an array, not a "+asyncValueList+" for path="+cursor.atomPath);
}
fork icon6
star icon115
watch icon0

21
22
23
24
25
26
27
28
29
30
31
32
33
34


const prometheusConsumer = sourceCode('src/lib/pullConsumers/Prometheus');


moduleCache.remember();


const arraysToPromLines = (input) => lodash.flatten(input).join('\n');


describe('Prometheus Pull Consumer', () => {
    let context;
    let eventStub;
fork icon23
star icon49
watch icon20

Ai Example

1
2
3
4
5
6
7
const _ = require("lodash");

const nestedArray = [1, [2, [3, [4]], 5]];

const flattenedArray = _.flatten(nestedArray);

console.log(flattenedArray); // [1, 2, 3, 4, 5]

In this example, the nestedArray contains three levels of nesting. lodash.flatten recursively flattens the array, creating a new, flattened array containing all the values. The flattened array is then logged to the console.

46
47
48
49
50
51
52
53
54
55
56
}


async function  getPopData(populateDocs, populateOptions, mongoDocs, schema, schemaOptions = undefined) {
    let localField = schemaOptions && schemaOptions.localField ? schemaOptions.localField : populateOptions.path;
    let foreignField = schemaOptions && schemaOptions.foreignField ? schemaOptions.foreignField : '_id';
    let ids = _.flatten(mongoDocs.map((m) => m[localField]));
    if (!ids || !ids.length) return;
    let popCollection = getPopCollection(schema, populateOptions.path.split('.'));
    popCollection = popCollection.toLowerCase() + 's';

fork icon8
star icon454
watch icon7

44
45
46
47
48
49
50
51
52
53
    initial: '{}',
    validate: value => !_.isEmpty(_.trim(value)) && isJson(_.trim(value)) || 'Invalid initialization args - inform a valid JSON string',
  },
]);

const flags = _.flatten([
  confirm ? [] : ['--yes'],
]).filter(_.isString);

return {
fork icon21
star icon36
watch icon10

46
47
48
49
50
51
52
53
54
55
    validate: value => _.isEmpty(_.trim(value)) || isArchwayAddress(_.trim(value)) || 'Invalid address',
    format: value => _.trim(value),
  },
]);

const extraFlags = _.flatten([
  confirm ? [] : ['--yes'],
]).filter(_.isString);

return {
fork icon21
star icon36
watch icon10

1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
console.log('conMentoringSessions', allConMentoringSessions.length)
console.log(
  'tpCompanyProfiles',
  allUsers.map((p) => p.tpCompanyProfile).filter((p) => p).length
)
const allJobListings = _.flatten(allUsers.map((p) => p.tpJobListings))
console.log('tpJobListings', allJobListings.length)
console.log(
  'tpJobsekeerProfiles',
  allUsers.map((p) => p.tpJobseekerProfile).filter((p) => p).length
fork icon7
star icon18
watch icon6

+ 27 other calls in file

3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
  }


  return fieldSet.fields;
}
function getFieldSetsFields(fieldSets) {
  return lodash.flatten(fieldSets.map(getFieldSetFields));
}
function getUnsortedOptions(fieldConfig, injected) {
  var options = fieldConfig.options,
      optionType = fieldConfig.optionType;
fork icon3
star icon15
watch icon0

9
10
11
12
13
14
15
16
17
18
19
 * @param {string} path                        - The operation path
 * @param {Array.<string|Array.<string>>} args - The desired arguments
 * @returns {Array.<Object>} The matching parameters
 */
exports.mapArgs = (spec, name, method, path, args) => {
    const allBridgeParams = _.flatten(args)


    // Prevent dupes
    const byName = _.groupBy(allBridgeParams)
    Object.keys(byName).forEach(arg => {
fork icon4
star icon9
watch icon0

44
45
46
47
48
49
50
51
52
53
54
55
56
    params.push(tokenParams);
  }


  const query = expression(field, tokensMatch(paramRefs, partialMatch));


  return [query, flatten(params)];
};


const buildMultiTokenMatch = (field, prop, value) => {
  const options = {
fork icon13
star icon8
watch icon7

+ 9 other calls in file

4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
},

// Returns an array built from the contents of a given array repeated
// a certain number of times.
cycle: function(t, elems) {
  return _.flatten(_.times(t, function() { return elems; }), true);
},

// Returns an array with two internal arrays built from
// taking an original array and spliting it at an index.
fork icon3
star icon2
watch icon1

+ 235 other calls in file

51
52
53
54
55
56
57
58
59
60
var devGlobs = slave.json.dev;
var injectionByBuildFiles = slave.json.build;

// gather slave dev files
return _.mapValues(injectionByBuildFiles, function(injectTasks, buildFile) {
    return _.flatten(injectTasks.map(function (injectTaskName) {
        if (!devGlobs.hasOwnProperty(injectTaskName))
            return [];
        else
            return devGlobs[injectTaskName]
fork icon3
star icon2
watch icon0

29
30
31
32
33
34
35
36
37
38

function main (filePath$, packagePath, prepend, blockScope, nonstop, preventEval, includePrevented, silence, debug, output, delimeter) {
  var logStore = []
  DEBUG = debug
  log = logFactory(logStore, silence)
  var filePaths = _.flatten([filePath$])
  logInfo('it worked if it ends with', 'ok')
  return getPackage(packagePath)
  .then(function (pkg) {
    return Promise.map(filePaths, function (filePath) {
fork icon0
star icon1
watch icon2

+ 7 other calls in file

357
358
359
360
361
362
363
364
365
366
$scope.haeLajitunnus = function (organisaatioid) {
  return _.find($rootScope.organisaatiot, {'id': organisaatioid}).lajitunnus;
};

$scope.sumHaettavaAvustus = function () {
  var avustuskohteet = _.flatten(_.map($scope.avustuskohdeluokat, function (l) {
    return l.avustuskohteet;
  }));
  return _.sumBy(avustuskohteet, _.partial(h.avustuskohdeRahamaara, 'haettavaavustus'));
};
fork icon2
star icon0
watch icon0

45
46
47
48
49
50
51
52
53
54
55
56
57
console.log(findLastIndex); // => 2


const firstHead = _.first([1, 2, 3]);
console.log(firstHead); // => 1


const flatten = _.flatten([1, [2, [3, [4]], 5]]);
console.log(flatten); // => [1, 2, [3, [4]], 5]


const flattenDeep = _.flattenDeep([1, [2, [3, [4]], 5]]);
console.log(flattenDeep); // => [1, 2, 3, 4, 5]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

61
62
63
64
65
66
67
68
    });
    return data.map(data => parseInt(data.split(':').pop(), 10));
  }
  async function getChildrenCids(cids, uid) {
    const childrenCids = await Promise.all(cids.map(cid => Categories.getChildrenCids(cid)));
    return await privileges.categories.filterCids('find', _.flatten(childrenCids), uid);
  }
};
fork icon1
star icon1
watch icon5

263
264
265
266
267
268
269
270
271
272

        // Drop any that aren't actual routes (middlewares, error handlers, etc.)
        return null;
    });

    return _.flatten(paths);
};

let paths = buildPaths(webserver.app._router.stack).filter(Boolean).map((pathObj) => {
    pathObj.path = pathObj.path.replace(/\/:([^\\/]+)/g, '/{$1}');
fork icon0
star icon2
watch icon5

292
293
294
295
296
297
298
299
300
301
  return Promise.all(allTasks)
})

const z3 = performance.now()
console.log('5.) Finished enumerating keys elipsed time ' + ((z3 - z2) / 1000) + ' from finised walking folders and ' + ((z2 - z0) / 1000) + ' from the beginning')
var allKeys = _.flatten(alltasksresolved)
var allKeys = allKeys.filter(item => item[0].endsWith('/') === false) // to remove directories
console.log('\nThe number of files in specified bucket(s) ' + allKeys.length + '. Current local time:' + commonshared.timeConverter(Date.now()) + '\n\n')

// TODO: dontwait for all files to be enumerated but do file enumeration and SQL population in parralell
fork icon0
star icon1
watch icon0

361
362
363
364
365
366
367
368
369
370
// We attach the workflow template step override options to the workflow step for easy access
if (_.isEmpty(templateSelectedStep)) {
  // Since we don't have a template selected step, we allow all possible overrides
  stepResult.propsOverrideOption = { allowed: ['title', 'desc', 'skippable'] };
  stepResult.configOverrideOption = {
    allowed: _.flatten(
      _.map(_.get(stepTemplate, 'inputManifest.sections', []), section => findConfigNames(section)),
    ),
  };
} else {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

Other functions in lodash

Sorted by popularity

function icon

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