
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
Merge 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