
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Flatten an array in JavaScript.
- Flatten array to 1 line in JavaScript
- Best way to flatten an object with array properties into one array JavaScript
- Deep count of elements of an array using JavaScript
- Function to flatten array of multiple nested arrays without recursion in JavaScript
- How would you deep copy an Object in Javascript?
- Explain Deep cloning an object in JavaScript with an example.
- How to Flatten JavaScript objects into a single-depth Object?
- How to flatten an input tensor by reshaping it in PyTorch?
- In Javascript how to empty an array
- How to empty an array in JavaScript?
- How to truncate an array in JavaScript?
- How to convert an object into an array in JavaScript?
- What is the most efficient way to deep clone an object in JavaScript?
- How to convert nested array pairs to objects in an array in JavaScript ?

Advertisements