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.
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.
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]
flattenArray
that takes an array as an argument.result
, which will eventually hold our flattened result.forEach
, we loop over each item in the input array.Array.isArray()
.flattenArray
recursively on that item. The result of this call is concatenated to our existing result
.result
.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]
flattenArrayIterative
function.result
to store the flattened result and a stack
variable initialized with a copy of the input array (...arr
).stack
.result
.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.
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
15/10/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS
14/09/2024 | VanillaJS
14/09/2024 | VanillaJS
12/09/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS