javascript
Lodash - Flatten an array to a fixed depth
In lodash, you can flatten the array to a fixed level using flattenDepth method. You just need to pass the depth level value to the method.
const arr = [
[10], [20, 30, [40, [50]]], 60, [70, [80]]
];
//Flatten to 1 level
const result_1 = _.flattenDepth(arr, 1);
// => [10,20,30,[40,[50]],60,70,[80]]
//Flatten to 2 level
const result_2 = _.flattenDepth(arr, 2);
// => [10,20,30,40,[50],60,70,80]
In the code snippet, we are flattening an array - arr to level 1 depth and level 2 depth.
_.flattenDepth Lodash
_.flattenDepth(Array, Depth=1)
Argument passed description
Array: [Required] The array that you want to flatten to a fixed depth.
Depth: [Optional] The depth level value to which you want to flatten your array. The default value for this is 1 means if you do not pass any value to it. It will flatten the array to level 1.
Example Demo
Was this helpful?
Similar Posts
- Break an array into fixed length array groups using lodash in Javascript
- Lodash - Flatten an array to single level deep
- Lodash - Flatten an array to multi levels deep
- Parenthesis Validation, Max Depth and Max Breadth - Braze - Full Stack - 12/20/21
- Create fixed length array with blank values in it Javascript
- Assign fixed width to the columns of bar chart in Chart.js
- Assign a fixed height to chart in Chart.js