Open In App

Implement Custom Array Flat method in JavaScript

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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.

Example: The below code uses Recursion to flatten the array.

JavaScript
function customFlat(arr) {
    return arr.reduce((acc, val) => 
    acc.concat(Array.isArray(val) ? 
    customFlat(val) : val), []);
}

const nestedArray = [1, [2, 3], [4, [5, 6]]];
console.log("Flattened array is: ")
console.log(customFlat(nestedArray));

Output
Flattened array is: 
[ 1, 2, 3, 4, 5, 6 ]

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.

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
]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads