29/10/2024
Flattening an array means converting a multi-dimensional array into a one-dimensional array. For instance, if we have an array like [1, [2, [3, 4], 5], 6]
, the goal is to transform it into [1, 2, 3, 4, 5, 6]
.
Here’s how we can achieve this using a simple function in JavaScript.
Before we dive into the code, let’s clarify what our function will do:
Recursion is a powerful tool for solving problems that can be broken down into smaller sub-problems. In our case, we can traverse each element of the array, check if it’s an array itself, and if so, call our function again until we get to a non-array element.
Here’s a simple implementation:
function flattenArray(arr) { // Initialize an empty array to hold the result let result = []; // Loop through each element of the input array for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { // If the current element is an array, recurse into it result = result.concat(flattenArray(arr[i])); } else { // If the current element is not an array, add it to the result result.push(arr[i]); } } return result; } // Example usage: const nestedArray = [1, [2, [3, 4], 5], 6]; console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4, 5, 6]
function flattenArray(arr)
, where arr
is our input nested array.result
to store our flattened elements.arr
.
Array.isArray(arr[i])
, we determine if the current element is an array.
flattenArray(arr[i])
to flatten that sub-array, and concatenate it to result
using result.concat()
.result
using result.push(arr[i])
.result
array.flattenArray([])
will return an empty array []
as expected.[1, 2, 3]
), it will return the same array, as there are no nested elements.This method is straightforward and leverages the simplicity of recursion to handle arrays of varying depths. In scenarios where performance is critical or very deep nesting is expected, consider iterative methods or using a stack to avoid potential stack overflow issues with recursion.
With this approach, you can take any complex nested structure and get the clean, flat array you need!
29/10/2024 | VanillaJS
17/11/2024 | VanillaJS
17/11/2024 | VanillaJS
29/10/2024 | VanillaJS
17/11/2024 | VanillaJS
17/11/2024 | VanillaJS
17/11/2024 | VanillaJS