Syntax, Parameter and Return Value
Syntax:
_.flattenDepth(array, [depth=1])
Parameters:
-
array (Array): The array to flatten.
- [depth=1] (number): The maximum recursion depth.
Return Value:
(Array) - Returns the new flattened array.
Examples
Basic Flattening:
JavaScript
var _ = require('lodash');
var array = [1, [2, [3, [4]], 5]];
var flattened = _.flattenDepth(array, 1);
console.log(flattened);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, [3, [4]], 5]
Here, _.flattenDepth() flattens the array one level deep.
Deep Flattening:
JavaScript
var flattenedDeep = _.flattenDepth(array, 2);
console.log(flattenedDeep);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3, [4], 5]
This example demonstrates flattening up to two levels.
Full Flattening:
JavaScript
var fullyFlattened = _.flattenDepth(array, Infinity);
console.log(fullyFlattened);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3, 4, 5]
Using Infinity as depth parameter fully flattens the nested array.
Flattening with Real-world Data:
JavaScript
var data = [[{ id: 1, name: 'John' }], [{ id: 2, name: 'Jane' }]];
var flattenedData = _.flattenDepth(data, 1);
console.log(flattenedData);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
This example shows _.flattenDepth() applied to an array of objects, a common scenario in data handling.
Frequently Asked Questions
Can _.flattenDepth() handle arrays with mixed data types?
Yes, it can flatten arrays containing a mix of data types, including numbers, strings, objects, and other arrays, up to the specified depth.
What happens if the depth parameter is omitted?
If omitted, _.flattenDepth() defaults to a depth of 1, flattening the array one level deep.
Is _.flattenDepth() efficient for large arrays?
While efficient for moderate-sized arrays, its performance may vary with very large or deeply nested arrays, and it's advisable to test for specific use cases.
Conclusion
The _.flattenDepth() method in Lodash is a powerful and flexible tool for developers to manage nested arrays in JavaScript. Its ability to control the depth of flattening makes it invaluable in data manipulation and parsing tasks. Understanding and utilizing this function can significantly streamline array operations, enhancing code readability and efficiency.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.