How to use indexOf Method In Javascript
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.
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.
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