
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Simplifying Nested Arrays in 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 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 ]
Advertisements