Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Flattening multi-dimensional arrays in JavaScript
JavaScript arrays can be nested to create multi-dimensional structures. Flattening converts these nested arrays into a single-level array. The flat() method provides a clean solution for this operation.
Syntax
array.flat(depth)
Parameters
depth (optional): The number of nested levels to flatten. Default is 1. Use Infinity to flatten all levels.
Basic Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Flattening Demo</title>
</head>
<body>
<h2>Flattening Multi-dimensional Arrays</h2>
<div id="output"></div>
<script>
let output = document.getElementById('output');
// Original nested array
let nestedArray = [1, 2, 3, [4, 5], [6, [7, 8]]];
output.innerHTML += '<p><strong>Original:</strong> ' + JSON.stringify(nestedArray) + '</p>';
// Flatten by depth 1 (default)
let flat1 = nestedArray.flat();
output.innerHTML += '<p><strong>Depth 1:</strong> ' + JSON.stringify(flat1) + '</p>';
// Flatten by depth 2
let flat2 = nestedArray.flat(2);
output.innerHTML += '<p><strong>Depth 2:</strong> ' + JSON.stringify(flat2) + '</p>';
// Flatten completely
let flatAll = nestedArray.flat(Infinity);
output.innerHTML += '<p><strong>All levels:</strong> ' + JSON.stringify(flatAll) + '</p>';
</script>
</body>
</html>
Output
Original: [1,2,3,[4,5],[6,[7,8]]] Depth 1: [1,2,3,4,5,[6,[7,8]]] Depth 2: [1,2,3,4,5,6,7,8] All levels: [1,2,3,4,5,6,7,8]
Different Flattening Methods
Using flat() with Different Depths
let arr = [1, [2, 3], [4, [5, 6]]];
console.log("Original:", arr);
console.log("Depth 1:", arr.flat(1));
console.log("Depth 2:", arr.flat(2));
console.log("All levels:", arr.flat(Infinity));
Original: [ 1, [ 2, 3 ], [ 4, [ 5, 6 ] ] ] Depth 1: [ 1, 2, 3, 4, [ 5, 6 ] ] Depth 2: [ 1, 2, 3, 4, 5, 6 ] All levels: [ 1, 2, 3, 4, 5, 6 ]
Using concat() and spread operator
let nestedArr = [[1, 2], [3, 4], [5, 6]];
// Method 1: Using concat with spread
let flattened1 = [].concat(...nestedArr);
console.log("Using concat:", flattened1);
// Method 2: Using flat()
let flattened2 = nestedArr.flat();
console.log("Using flat():", flattened2);
Using concat: [ 1, 2, 3, 4, 5, 6 ] Using flat(): [ 1, 2, 3, 4, 5, 6 ]
Comparison of Methods
| Method | Depth Control | Browser Support | Performance |
|---|---|---|---|
flat() |
Yes | ES2019+ | Excellent |
concat(...arr) |
One level only | All browsers | Good for shallow |
| Manual recursion | Full control | All browsers | Depends on implementation |
Real-world Example
// Processing nested data structures
let userData = [
["John", "Doe"],
["Jane", ["Smith", "Johnson"]],
[["Alice", "Bob"], "Wilson"]
];
// Flatten to get all names
let allNames = userData.flat(Infinity);
console.log("All names:", allNames);
// Filter and process
let validNames = allNames.filter(name => typeof name === 'string');
console.log("Valid names:", validNames);
All names: [ 'John', 'Doe', 'Jane', 'Smith', 'Johnson', 'Alice', 'Bob', 'Wilson' ] Valid names: [ 'John', 'Doe', 'Jane', 'Smith', 'Johnson', 'Alice', 'Bob', 'Wilson' ]
Key Points
-
flat()returns a new array; it doesn't modify the original - Default depth is 1 if no parameter is provided
- Use
Infinityto flatten all nested levels - Empty slots in sparse arrays are removed during flattening
Conclusion
The flat() method is the modern standard for flattening arrays in JavaScript. It provides precise depth control and excellent performance, making it ideal for processing nested data structures.
Advertisements
