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.
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