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 to create a unique array in JavaScript?
- How do I use Lodash to truncate a string in JavaScript?
- How do I use Lodash to get unique values in a JavaScript array?
- How can I use Lodash to capitalize a string in JavaScript?
- How can I use Lodash in a JavaScript REPL?
- How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
- How can I use lodash in a JavaScript sandbox?
- How can I remove a value from an array using JavaScript and Lodash?
See more codes...