Function to Flatten a Nested Array

JavaScript

Function to check if two strings are anagrams of each other:

You can create a JavaScript function to flatten a nested array using recursion. Here's how you can implement it:

js Copy Code
function flattenArray(arr) {
    let flattenedArray = [];

    // Iterate through each element in the array
    arr.forEach(element => {
        // If the element is an array, recursively flatten it
        if (Array.isArray(element)) {
            flattenedArray = flattenedArray.concat(flattenArray(element));
        } else {
            // If the element is not an array, push it to the flattened array
            flattenedArray.push(element);
        }
    });

    return flattenedArray;
}

// Example usage:
const nestedArray = [1, [2, 3], [4, [5, 6]]];
console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4, 5, 6]
Output:
[ 1, 2, 3, 4, 5, 6 ]

Explanation:

This function takes an array 'arr' as input and initializes an empty array 'flattenedArray' to store the flattened elements. It iterates through each element in the input array. If the element is an array, it recursively calls the 'flattenArray' function on that element and concatenates the result with the flattenedArray. If the element is not an array, it simply pushes it to the 'flattenedArray'. Finally, it returns the flattened array.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.