Simplifying nested array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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 fale values inside the array (NaN, undefined and null) with 0.

Therefore, let's write the code for this function −

Example

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 < arr.length; i++){
      if(Array.isArray(arr[i])){
         recursiveSimplify(arr[i]);
      }else if(!arr[i]){
         arr[i] = 0
      };
   };
};
recursiveSimplify(arr);
console.log(arr);

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
]
raja
Published on 28-Aug-2020 14:11:54
Advertisements