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.

JavaScript
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()

Similar Reads

Recursive approach

In the recursive approach we define a function flattenArray that takes a nested array as input and returns a flattened array. We iterate over each element of the input array. If an element in itself an array, we recursively call the flattenArray function on that element and concatenate the result with the result array. If an element is not an array we simply push it to the result array. This process continues until all elements of the nested array are processed....

Iterative approach

In the iterative approach, we use a stack data structure to flatten the nested array. We start by pushing all elements of the input array onto the stack. Then we enter a loop where we repeatedly pop an element from the stack. If the popped element is an array, we push its elements onto the stack. If the popped element is not an array, we add it to the beginning of the result array. We continue this process until the stack is empty....

Using Array.prototype.flat()

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....