How to use Iterative approach In Javascript

This approach uses a while loop to iterate over the array. It keeps track of the current index in the array and checks if the element at that index is an array. If it is an array, it flattens that array and inserts its elements into the original array at the current index.

Example: The below code uses an Iterative approach to flatten the array.

JavaScript
function customFlat(arr) {
    let flattened = [...arr];
    let i = 0;
    while (i < flattened.length) {
        if (Array.isArray(flattened[i])) {
            flattened.splice(i, 1, ...flattened[i]);
        } else {
            i++;
        }
    }
    return flattened;
}

// Example usage
const nestedArray = [1, [4, [5, 6]], [[8,9], 10]];
console.log(customFlat(nestedArray));

Output
[
  1, 4,  5, 6,
  8, 9, 10
]

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 approach
  • Using Iterative approach

Similar Reads

Using Recursion approach

This approach uses a recursive function to flatten the nested arrays. Here function checks each element of the array and if the element is an array then it recursively calls itself to flatten that array....

Using Iterative approach

This approach uses a while loop to iterate over the array. It keeps track of the current index in the array and checks if the element at that index is an array. If it is an array, it flattens that array and inserts its elements into the original array at the current index....