Open In App

How to Remove Null Objects from Nested Arrays in JavaScript ?

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Javascript arrays are a very flexible container that can hold both elements or values. Nevertheless, with nested arrays, it is crucial for data management and cleaning. Replacing null objects is a frequent demand.

Below are the methods to remove null objects from nested arrays in JavaScript:

Using Filter() Method

The filter() method in JavaScript creates a new array by applying a provided callback function to each element. This function returns true for elements that match a specified condition.

Example: In this code, the removeNullObjects function uses the filter() method to create a new array that only includes elements that are not null or undefined.

Javascript
let nestedArray =
    [1, null, [2, null], 3, null, 4, null, 5];

function removeNullValues(item) {

    // Recursively remove null values from nested arrays
    if (Array.isArray(item)) {
        const filteredArray = item
            .map((subItem) => removeNullValues(subItem))
            .flat(1)
            .filter((subItem) => 
                subItem !== null && subItem !== undefined);
        return filteredArray.length > 0 ? filteredArray : null;
    } else {
        // Remove null values from non-array items
        return item !== null && item !== undefined ? [item] : [];
    }
}

let newArray = 
    removeNullValues(nestedArray).filter(Boolean);
console.log(newArray);

Output
[ 1, 2, 3, 4, 5 ]

Explanation: Above code initializes an array named ‘array’ with a sequence of values, including null elements. The code defines a function called ‘removeNullObjects’ that utilizes the filter method to create a new array, ‘newArray,’ by excluding null and undefined elements from the original array. Upon invoking this function with the ‘array’ as an argument, the ‘newArray’ is generated, filtering out the null values. The resulting array, [1, 2, 3, 4, 5], is then printed to the console using console.log(). Therefore, the output of the code is the array without the null and undefined elements, showcasing the successful removal of these values from the original array.

Using Set Method

To remove null objects from nested arrays in JavaScript, the Set method can be used along with the filter function. By converting the nested arrays into Sets and then back into arrays, duplicates and null values are automatically eliminated, providing a clean array without null objects in a concise and efficient manner.

Example: In this example, the removeNullObjects function uses the Set to create a unique set of values, excluding null and undefined values. The spread (…) operator is then used to convert the set back to an array.

Javascript
let nestedArray = [1, null, [2, null], 3, null, 4, null, 5];

function removeNullValues(item) {
    if (Array.isArray(item)) {
    
        // Recursively remove null values from nested arrays
        const filteredArray = item
            .map((subItem) => removeNullValues(subItem))
            .flat(1);
        return [...new Set(filteredArray)].filter(
            (subItem) => 
                subItem !== null && subItem !== undefined,
        );
    } else {
    
        // Remove null values from non-array items
        return item !== null && item !== undefined ? [item] : [];
    }
}

let newArray = 
    removeNullValues(nestedArray).filter(Boolean);
console.log(newArray);

Output
[ 1, 2, 3, 4, 5 ]

Explanation: Provided array named ‘nestedArray,’ includes a sequence of values, including null elements. The code declares a function called ‘removeNullObjects,’ which utilizes the filter method to remove null and undefined elements from the original array. The array is then converted to a Set using the spread operator (‘…new Set(…)’), automatically eliminating duplicate values, including null. The resulting unique array is returned by the function and printed to the console using console.log(). Therefore, the output of the code is a new array [1, 2, 3, 4, 5, 6, 7], free of null and duplicate values.

Using forEach

To remove null objects from nested arrays in JavaScript using forEach, iterate over the outer array with forEach, and for each inner array, use filter to exclude null objects. Update the nested arrays in place, ensuring the removal of null elements within each subarray.

Example:In this code the forEach() method iterates over each element in the array, for array elements, the function is called recursively to remove null objects from nested arrays, for non-array elements, null objects are filtered out, the cleaned elements are then pushed into a new array.

Javascript
let nestedArray = [
    1,
    null,
    [2, 3, null, [4, null, 5]],
    6,
    undefined,
    [null, 7],
];

function removeNullObjects(arr) {
    let cleanedArray = [];

    arr.forEach((item) => {
        if (Array.isArray(item)) {
            let cleanedSubArray = removeNullObjects(item);
            if (cleanedSubArray.length > 0) {
                cleanedArray.push(cleanedSubArray);
            }
        } else {
            if (item !== null && item !== undefined) {
                cleanedArray.push(item);
            }
        }
    });

    return cleanedArray;
}

console.log(removeNullObjects(nestedArray));

Output
[ 1, [ 2, 3, [ 4, 5 ] ], 6, [ 7 ] ]

Explanation: Array, ‘nestedArray,’ containing various elements, including nested arrays and null values. The function called ‘removeNullObjects’ recursively traverses the ‘nestedArray.’ For each element, the function filters out null and undefined values, building a new array, ‘cleanedArray,’ without those elements. The recursive application ensures the removal of null objects from all levels of nesting. The final result ([1,[2,3[4,5]],6,[7]]) is printed to the console using console.log(). The output is an array where all null and undefined elements have been removed, maintaining the nested structure of the original array.

Using Reduce Method

To remove null objects from nested arrays in JavaScript using the reduce method, one can apply it along with filter to iterate through the nested arrays and eliminate elements that are null. The reduce method helps in combining the filtered results into a single array, effectively removing null objects from the nested structure.

Example: This removeNullObjects function uses the reduce() method to accumulate non-null values into a new array, and it also recursively processes nested arrays to remove null values.

Javascript
let nestedArray = [
    1,
    null,
    [2, 3, null, [4, null, 5]],
    6,
    undefined,
    [null, 7],
];

function removeNullObjects(arr) {
    return arr.reduce((accumulator, currentValue) => {
        if (Array.isArray(currentValue)) {
        
            // Recursively remove null values from nested arrays
            const cleanedArray = removeNullObjects(currentValue);
            if (cleanedArray.length > 0) {
                accumulator.push(cleanedArray);
            }
        } else if (currentValue !== null && currentValue !== undefined) {
        
            // Filter out null values
            accumulator.push(currentValue);
        }
        return accumulator;
    }, []);
}

console.log(removeNullObjects(nestedArray));

Output
[ 1, [ 2, 3, [ 4, 5 ] ], 6, [ 7 ] ]

Explanation: The provided JavaScript code defines a function ‘removeNullObjects’ to recursively remove null values from a nested array (‘nestedArray’). The code utilizes the reduce method, which iterates through the nested structure, filtering out both null and undefined values. For nested arrays, the function is applied recursively to ensure the removal of null values at all levels. The output, displayed using console.log(), is a cleaned version of the original nested array, free from null and undefined elements, resulting in [[1, [2, 3, [4, 5]], 6, [7]]].

Using indexOf Method

The indexOf method can be used in combination with the filter method. Iterate through the outer array and apply filter to each inner array using indexOf(null) to exclude null objects, resulting in a cleaned nested array without null values.

Example: The removeNullObjects function uses the indexOf() method within a loop to iterate over the array. For nested arrays, it recursively calls itself to handle nested structures. This approach ensures that all occurrences of null values are removed from the array.

Javascript
let nestedArray = [
    1,
    null,
    [2, 3, null, [4, null, 5]],
    6,
    undefined,
    [null, 7],
];

function removeNullObjects(arr) {
    let cleanedArray = [];

    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
        
            // Recursively remove null values from nested arrays
            let nestedCleanedArray = removeNullObjects(arr[i]);
            if (nestedCleanedArray.length > 0) {
                cleanedArray.push(nestedCleanedArray);
            }
        } else if (arr[i] !== null && arr[i] !== undefined) {
        
            // Filter out null values
            cleanedArray.push(arr[i]);
        }
    }

    return cleanedArray;
}

console.log(removeNullObjects(nestedArray));

Output
[ 1, [ 2, 3, [ 4, 5 ] ], 6, [ 7 ] ]

Explanation: The provided JavaScript code defines an array named ‘nestedArray’ containing a mix of values and nested arrays, including null and undefined elements. The code declares a function ‘removeNullObjects’ that recursively traverses the nested arrays, filtering out null and undefined values. The cleaned array, free of null and undefined elements, is then printed to the console using console.log(). Therefore, the output of the code is a new array representing ‘nestedArray’ with all null and undefined values removed, creating a sanitized nested structure with non-null elements only.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads