How to use Array.prototype.flat() In Javascript
In this approach we use flat() method which is used to flatten the nested array. This method returns a new array with all the elements from the nested arrays concatenated into one array.
Example: Below example uses Array.prototype.flat() to transform nested array into normal array.
let nestedArray = [1, [2, [3, 4], 5], 6];
let flattenedArray = nestedArray.flat(Infinity);
console.log(flattenedArray);
Output
[ 1, 2, 3, 4, 5, 6 ]
Time complexity: O(n)
Space complexity: O(n)
JavaScript Program to Transform Nested Array into Normal Array
JavaScript allows us to convert nested arrays into a single, flat array using JavaScript. By simplifying nested structures, you can enhance the manageability and readability of your code.
Example:
Input: [[1, 2], [3, [4, 5]]] Output: [1, 2, 3, 4, 5]
Below are the approaches to transform nested arrays into normal arrays with JavaScript:
Table of Content
- Recursive approach
- Iterative approach
- Using Array.prototype.flat()