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 Lodash to truncate a string in JavaScript?
- 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 can I use lodash's `some()` method to achieve the same result as the JavaScript `some()` method?
- How can I use Lodash to create a unique array in JavaScript?
- How can I use Lodash's reject function in JavaScript?
- How do I remove a property from an object using Lodash in JavaScript?
- How can I use Lodash in my online JavaScript project?
- How do I use the Lodash includes method in JavaScript?
- How do I use Lodash's pick() method in JavaScript?
See more codes...