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
 
How to deep flatten an array in JavaScript?
Flattening an array
Flattening an array is nothing but merging a group of nested arrays present inside a provided array.
Flattening of an array can be done in two ways.
1) concat.apply()
In the following example there are some nested arrays containing elements 3,4,5 and 6. After flattening them using concat() method we get the output as 1,2,3,4,5,6,9.
Example
<html> <body> <script> var arrays = [1,2,[3,4,[5,6]],9]; var merged = [].concat.apply([], arrays); documemt.write(merged); </script> </body> </html>
Output
1,2,3,4,5,6,9
2) array.flat()
In the following example there are some nested elements such as 2,3,4,5,6,9. After Flattening them using array.flat() method we get the output as 1,2,2,3,4,5,6,9.
Example
<html> <body> <script> const arrays = [1,2,[2,3,[4,5,[6,9]]]]; const merged = arrays.flat(2); document.write(merged) </script> </body> </html>
Output
1,2,2,3,4,5,6,9
Advertisements