- Trending Categories
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
Flatten an array in JavaScript.
We are required to write a JavaScript array function that takes in a nested array and returns an array with all the elements present in the array without any nesting.
For example −
//if the input is: const arr = [[1, 2, 3], [4, 5], [6]]; //then the output should be: const output = [1, 2, 3, 4, 5, 6];
Therefore, let’s write the code for this function −
Method 1: Using recursion
Here we will loop over the original nested array and recursively push the nested element elements into a new array.
Example
const arr = [[1, 2, 3], [4, 5], [6]]; const flatten = function(){ let res = []; for(let i = 0; i < this.length; i++){ if(Array.isArray(this[i])){ res.push(...this[i].flatten()); } else { res.push(this[i]); }; }; return res; }; Array.prototype.flatten = flatten; console.log(arr.flatten());
Method 2: Using Arrray.prototype.reduce()
Here we will use the reduce() method to construct a new array like this −
Example
const arr = [[1, 2, 3], [4, 5], [6]]; const flatten = function(){ return this.reduce((acc, val) => { return acc.concat(...val); }, []); }; Array.prototype.flatten = flatten; console.log(arr.flatten());
Output
The console output for both of the methods will be −
[ 1, 2, 3, 4, 5, 6 ]
Advertisements