- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flattening a deeply nested array of literals in JavaScript
We are required to write a JavaScript function that takes in a nested array of literals as the only argument. The function should construct a new array that contains all the literal elements present in the input array but without nesting.
For example −
If the input array is −
const arr = [ 1, 3, [5, 6, [7, [6, 5], 4], 3], [4] ];
Then the output array should be −
const output = [1, 3, 5, 6, 7, 6, 5, 4, 3, 4];
Example
Following is the code −
const arr = [ 1, 3, [5, 6, [7, [6, 5], 4], 3], [4] ]; const flattenArray = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const el = arr[i]; if(Array.isArray(el)){ res.push(...flattenArray(el)); }else{ res.push(el); }; }; return res; }; console.log(flattenArray(arr));
Output
Following is the output on console −
[ 1, 3, 5, 6, 7, 6, 5, 4, 3, 4 ]
Advertisements