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?