Flattening an array with truthy/ falsy values without using library functions - JavaScript

We need to write a JavaScript function that takes a nested array containing falsy values and returns a completely flattened array. This means converting a multi-dimensional array into a single-dimensional array while preserving all elements, including falsy values like false, null, and 0.

For example, if the input is:

const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];

The output should be:

[1, 2, 3, 4, 5, 5, false, 6, 5, 8, null, 6]

Method 1: Using Recursive Function with Array.prototype Extension

We can extend the Array prototype to add a custom flatten method that recursively processes nested arrays:

const arr = [[1, 2, 3], [4, 5, [5, false, 6, [5, 8, null]]], [6]];

const flatten = function(){
    let res = [];
    for(let i = 0; i 

[
  1, 2, 3,    4,
  5, 5, false, 6,
  5, 8, null,  6
]

Method 2: Using Standalone Recursive Function

A cleaner approach is to create a standalone function without modifying the Array prototype:

function flattenArray(arr) {
    let result = [];
    for (let i = 0; i 

[
  1, 2, 3,    4,
  5, 5, false, 6,
  5, 8, null,  6
]

Method 3: Using While Loop with Stack Approach

An iterative approach using a stack to avoid potential recursion depth issues:

function flattenIterative(arr) {
    let result = [];
    let stack = [...arr];
    
    while (stack.length) {
        let next = stack.pop();
        if (Array.isArray(next)) {
            stack.push(...next);
        } else {
            result.push(next);
        }
    }
    
    return result.reverse();
}

const testArray = [[1, 2], [3, [4, false, null]], [5]];
console.log(flattenIterative(testArray));
[ 1, 2, 3, 4, false, null, 5 ]

How It Works

The recursive approach works by:

  • Iterating through each element in the array
  • Checking if the element is an array using Array.isArray()
  • If it's an array, recursively calling the flatten function on it
  • If it's not an array, adding it directly to the result
  • Using the spread operator (...) to merge flattened sub-arrays

Key Points

  • The function preserves all values, including falsy ones like false, null, 0, and undefined
  • It handles arrays of any nesting depth
  • The recursive approach is intuitive but may have stack overflow issues with very deep nesting
  • The iterative approach using a stack is more memory-efficient for deeply nested arrays

Conclusion

Custom flattening functions give you complete control over the flattening process while preserving all elements including falsy values. The recursive approach is most readable, while the iterative stack method handles extreme nesting better.

Updated on: 2026-03-15T23:18:59+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements