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 can I use Lodash to manipulate JavaScript objects online?
- How do I use Lodash in a JavaScript playground?
- How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
- How do I use Lodash to truncate a string in JavaScript?
- How can I check for undefined values in JavaScript using Lodash?
- How can I use Lodash to union two JavaScript arrays?
- How do I get the last element in an array using Lodash in JavaScript?
- How can I use Lodash to remove undefined values from an object in JavaScript?
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I use Lodash to find the unique key of a JavaScript object?
See more codes...