Simplifying nested array JavaScript

Let's say, we have an array of arrays that contains some elements like this ?

const arr = [3, 5, 7, 2, [4, NaN, null, 4, 8, [3, undefined, 24, null], null, 5, 1], NaN, 45, 2, 1];

Our job is to write a recursive function that takes in this nested array and replaces all the falsy values inside the array (NaN, undefined and null) with 0.

Understanding Falsy Values

In JavaScript, falsy values include:

  • null
  • undefined
  • NaN
  • 0
  • "" (empty string)
  • false

Our function will target null, undefined, and NaN specifically.

Recursive Solution

The recursive approach checks each element: if it's an array, it calls itself recursively; if it's a falsy value, it replaces it with 0.

const arr = [3, 5, 7, 2, [4, NaN, null, 4, 8, [3, undefined, 24, null],
null, 5, 1], NaN, 45, 2, 1];

const recursiveSimplify = (arr) => {
    for(let i = 0; i 

Output

The output in the console will be ?

[
    3,
    5,
    7,
    2,
    [ 4, 0, 0, 4, 8, [ 3, 0, 24, 0 ], 0, 5, 1 ],
    0,
    45,
    2,
    1
]

How It Works

The function iterates through each element of the array:

  1. If the element is an array, it calls recursiveSimplify on that nested array
  2. If the element is falsy (!arr[i] returns true), it replaces it with 0
  3. Otherwise, it leaves the element unchanged

Alternative: Non-Mutating Approach

If you prefer not to modify the original array, here's a version that returns a new array:

const arr = [3, 5, 7, 2, [4, NaN, null, 4, 8, [3, undefined, 24, null]], NaN];

const simplifyArray = (arr) => {
    return arr.map(item => {
        if (Array.isArray(item)) {
            return simplifyArray(item);
        }
        return item || item === 0 ? item : 0;
    });
};

const result = simplifyArray(arr);
console.log(result);
[ 3, 5, 7, 2, [ 4, 0, 0, 4, 8, [ 3, 0, 24, 0 ] ], 0 ]

Conclusion

Recursive functions are ideal for processing nested arrays. The key is to check if each element is an array itself, then apply the same logic recursively. This approach handles arrays of any nesting depth.

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

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements