How to use forEach In Javascript
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.
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.
How to Remove Null Objects from Nested Arrays in JavaScript ?
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:
Table of Content
- Using Filter() Method
- Using Set Method
- Using forEach
- Using Reduce Method
- Using indexOf Method