Flattening a nested array refers to converting an array that contains other arrays into a single-level array. For instance, if you have an array like [1, [2, [3, 4], 5], 6]
, the goal is to transform it into [1, 2, 3, 4, 5, 6]
.
While the flat()
function available in modern JavaScript can accomplish this efficiently, it's beneficial to understand how we can do it using plain loops and recursion.
Example of a Nested Array
Let’s use a nested array for our example:
const nestedArray = [1, [2, [3, 4], 5], 6];
Here's how we can flatten this array without using the flat()
function.
Method 1: Using Recursion
One approach to flatten a nested array is through recursion. The idea is to iterate through each element of the array. If an element is an array, we call the function again on that array. If it's not, we add it directly to the result.
Here’s how we can implement this:
function flattenArray(arr) { let result = []; arr.forEach(item => { if (Array.isArray(item)) { result = result.concat(flattenArray(item)); // Recurse if the item is an array } else { result.push(item); // Add the item if it's not an array } }); return result; } const flattened = flattenArray(nestedArray); console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]
Explanation of the Code:
- We define a function
flattenArray
that takes an array as an argument. - We initiate an empty array
result
, which will eventually hold our flattened result. - Using
forEach
, we loop over each item in the input array. - Inside the loop, we check if the current item is an array using
Array.isArray()
. - If it is an array, we call
flattenArray
recursively on that item. The result of this call is concatenated to our existingresult
. - If the item is not an array, we simply push it to the
result
. - Finally, we return the fully flattened array.
Method 2: Using Iteration with a Stack
Another approach to flatten a nested array is to use an iterative method with a stack. This method avoids recursion, which can be beneficial when working with very deeply nested arrays. Here’s how to implement it:
function flattenArrayIterative(arr) { const result = []; const stack = [...arr]; // Spread the original array into a stack while (stack.length) { const item = stack.pop(); // Take the last item from the stack if (Array.isArray(item)) { stack.push(...item); // Push the elements of the array onto the stack } else { result.push(item); // If not an array, add it to the result } } return result.reverse(); // Reverse the result to maintain order } const flattenedIterative = flattenArrayIterative(nestedArray); console.log(flattenedIterative); // Output: [1, 2, 3, 4, 5, 6]
Explanation of the Code:
- We define the
flattenArrayIterative
function. - We initialize an empty array
result
to store the flattened result and astack
variable initialized with a copy of the input array (...arr
). - We use a while loop that runs as long as there are elements in the
stack
. - Inside the loop, we pop the last element from the stack.
- If the popped item is an array, we spread its elements and push them back onto the stack.
- If it’s not an array, we push it directly to the
result
. - Once the stack is empty, we return the
result
reversed to maintain the original order of elements.
By leveraging these techniques, you gain a deeper understanding of how to handle and manipulate arrays in JavaScript without relying solely on built-in functions.