 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Merging nested arrays to form 1-d array in JavaScript
Problem
We are required to write a JavaScript function that takes in two nested arrays, arr1 and arr2, as the first and the second argument.
Our function should create and return a third array that contains all the elements of arr1 and arr2 but flattened to single dimension
For example, if the input to the function is −
const arr1 = [ 1, [ 2, [ 4, 5, [ 6 ] ] ] ]; const arr2 = [ 11, 12, [ 16, 18, [ 19, 21, [ 23 ] ] ] ];
Then the output should be −
const output = [1, 2, 4, 5, 6, 11, 12, 16, 18, 19, 21, 23];
Example
Following is the code −
const arr1 = [    1, [       2, [          4, 5, [             6          ]       ]    ] ]; const arr2 = [    11, 12, [       16, 18, [          19, 21, [             23          ]       ]    ] ]; const flattenAndMerge = (arr1 = [], arr2 = []) => {    const res = [];    const flatten = (arr = []) => {       for(let i = 0; i < arr.length; i++){          if(Array.isArray(arr[i])){             flatten(arr[i]);          }else if(typeof arr[i] === 'number'){             res.push(arr[i])          };       };    };    flatten(arr1);    flatten(arr2);    return res; }; console.log(flattenAndMerge(arr1, arr2)); Output
Following is the console output −
[ 1, 2, 4, 5, 6, 11, 12, 16, 18, 19, 21, 23 ]
Advertisements
 