javascript-lodashHow do I flatten a nested array using Lodash in JavaScript?
Using Lodash, you can flatten a nested array in JavaScript with the _.flatten()
method.
Example
let array = [1, [2, [3, [4]], 5]];
let flattenedArray = _.flatten(array);
console.log(flattenedArray);
Output example
[1, 2, 3, 4, 5]
The _.flatten()
method takes a nested array as an argument and returns a flattened array. In the example above, the nested array [1, [2, [3, [4]], 5]
is flattened into a single-level array [1, 2, 3, 4, 5]
.
The _.flatten()
method also takes an optional argument of depth
which specifies how deep the flattening should be. If depth
is not specified, the array will be flattened to a single level.
The _.flatten()
method is part of the Lodash library and can be imported into your project using import _ from 'lodash'
or const _ = require('lodash')
.
Helpful links
More of Javascript Lodash
- How do I use yarn to install and use lodash in a JavaScript project?
- How do I use Lodash in a JavaScript playground?
- How can I use lodash in a JavaScript sandbox?
- How do lodash and underscore differ in JavaScript?
- How do I use Lodash to get unique values in a JavaScript array?
- How can I use Lodash's throttle function in JavaScript?
- How can I check for undefined values in JavaScript using Lodash?
- How do I use Lodash to truncate a string in JavaScript?
- How can I use Lodash to create a unique array in JavaScript?
- How do I use Lodash to zip two JavaScript arrays together?
See more codes...