JavaScript Program to Transform Nested Array into Normal Array
Last Updated :
09 May, 2024
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:
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.
Example: Below example uses recursive approach to transform nested array into normal array.
JavaScript
function flattenArray(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
// If element is an array,
// recursively flatten it
result = result
.concat(flattenArray(arr[i]));
} else {
// Otherwise add the element
// to the flattened array
result
.push(arr[i]);
}
}
return result;
}
const nestedArray = [[1, 2], [3, [4, 5]]];
console.log(flattenArray(nestedArray));
Time complexity: O(n), where n is the total number of elements in the nested array.
Space complexity: O(n)
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.
Example: Below example uses iterative approach to transform nested array into normal array.
JavaScript
function flattenArray(arr) {
let stack = [...arr];
let result = [];
while (stack.length > 0) {
let current = stack.pop();
if (Array.isArray(current)) {
// If current element is an array,
// push its elements onto the stack
stack
.push(...current);
} else {
// Otherwise, add the element
// to the result array
result
.unshift(current);
}
}
return result;
}
const nestedArray = [[4, 3], [8, 2], [9, 5]];
console.log(flattenArray(nestedArray));
Output[ 4, 3, 8, 2, 9, 5 ]
Time complexity: O(n)
Space complexity: O(n)
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.
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)
Similar Reads
JavaScript Program to Convert Byte Array to JSON In this article, we are going to learn about the conversion of a Byte Array into JSON. Converting a byte array to JSON means transforming a sequence of bytes into a structured JSON format, often involving decoding bytes to a text string and then parsing it into JSON data.Example:Input : [71, 101, 10
3 min read
Convert 2D Array to Object using Map or Reduce in JavaScript Converting a 2D array to an object is a common task in JavaScript development. This process involves transforming an array where each element represents a key-value pair into an object where keys are derived from one dimension of the array and values from another. Problem Description:Given a 2D arra
2 min read
Implement Custom Array Flat method in JavaScript The flat() method in JavaScript is used to flatten nested arrays. By using that function we can directly convert any type of array into 1D array. These are the following approaches to implementing a custom array flat method in JavaScript: Table of Content Using Recursion approachUsing Iterative appr
2 min read
How to Create Nested Arrays from a Nest of Arrays in JavaScript ? Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional struct
3 min read
How to Convert JSON Array to String Array in Java? JSON stands for JavaScript Object Notation. It is one of the widely used formats to exchange data by web applications. JSON arrays are almost the same as arrays in JavaScript. They can be understood as a collection of data (strings, numbers, booleans) in an indexed manner. Given a JSON array, we wil
3 min read
Java Program to Change a Collection to an Array An array is a data structure that can hold a fixed-size, homogeneous collection of elements of the same data type, which can be either primitive data types (e.g., int, float) or object references. However, the size of the array cannot be changed once it is created. On the other hand, a collection is
3 min read
How to flatten array with the JavaScript/jQuery? Flattening an array in JavaScript or jQuery involves transforming a nested array into a single-level array. This process is essential for simplifying complex data structures and making it easier to manipulate and access array elements. Below are the approaches to flatten an array with JavaScript/Jqu
3 min read
How to Convert an ArrayList of Objects to a JSON Array in Java? In Java, an ArrayList is a resizable array implementation of the List interface. It implements the List interface and is the most commonly used implementation of List. In this article, we will learn how to convert an ArrayList of objects to a JSON array in Java. Steps to Convert an ArrayList of Obje
3 min read
How to Convert an ArrayList Containing Integers to Primitive Int Array? In Java, ArrayList is the pre-defined class of the Java Collection Framework. It is part of the java.util package. ArrayList can be used to add or remove an element dynamically in the Java program. It can be snipped dynamically based on the elements added or removed into the ArrayList. In this artic
2 min read
Java Program to Implement Unrolled Linked List An Unrolled Linked List is a special type of Linked List in which each node stores an array of elements, unlike a simple linked list. Here we use an ArrayList and a constructor that initializes the size of the Unrolled Linked List. Elements are added to the first Node until it is filled and then a n
5 min read