Syntax, Parameter, and Return Value
Syntax:
_.flatten(array)
Parameters:
array (Array): The array to flatten.
Return Value:
A new array that is a one-level flat version of the input array.
Examples
Basic Usage:
Flattening a two-dimensional array.
JavaScript
let nestedArray = [1, [2, 3], [4, [5, 6]]];
let flatArray = _.flatten(nestedArray);
console.log(flatArray);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3, 4, [5, 6]]
Arrays of Objects:
Flattening an array containing nested arrays of objects.
JavaScript
let users = [{ name: 'Alice' }, [{ name: 'Bob' }, { name: 'Carol' }]];
let flattenedUsers = _.flatten(users);
console.log(flattenedUsers);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[{ name: 'Alice' }, { name: 'Bob' }, { name: 'Carol' }]
Complex Nested Arrays:
Demonstrating the limitation of one-level flattening.
JavaScript
let complexArray = [1, [2, [3, 4]], 5];
let result = _.flatten(complexArray);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, [3, 4], 5]
Chaining with Other Operations:
Using _.flatten() in conjunction with other Lodash methods.
JavaScript
let numbers = [[1, 2], [3, 4]];
let sum = _.chain(numbers).flatten().reduce((sum, n) => sum + n, 0).value();
console.log(sum);

You can also try this code with Online Javascript Compiler
Run Code
Output:
10
Frequently Asked Questions
Does _.flatten() affect deeply nested arrays?
_.flatten() only flattens the array one level deep. For deeper flattening, other methods like _.flattenDeep() or _.flattenDepth() are needed.
Is the original array modified by _.flatten()?
No, _.flatten() returns a new array, leaving the original array unchanged.
How does _.flatten() compare with native JavaScript flattening methods?
Native JavaScript methods like Array.prototype.flat() can achieve similar results, but _.flatten() offers consistent behavior across different JavaScript versions and environments.
Conclusion
Lodash's _.flatten() method is a practical tool for simplifying complex, nested arrays by reducing them to a single-level structure. This functionality is particularly useful in data processing, UI development, and handling nested data structures. The method enhances code clarity and efficiency, making the handling of multi-dimensional arrays more straightforward and manageable.
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.