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
Transform nested array into normal array with JavaScript?
In JavaScript, nested arrays can be flattened into a single-level array using several methods. The most common approach is the flat() method, which removes one level of nesting by default.
What is Array Flattening?
Array flattening transforms a nested array structure into a single-dimensional array. For example, converting [[1, 2], [3, 4]] into [1, 2, 3, 4].
Using flat() Method
The flat() method creates a new array with sub-array elements flattened into it. Here's how to flatten a nested array containing objects:
const arrayObject = [
[
{
Name: "John"
},
{
countryName: "US"
}
],
[
{
subjectName: "JavaScript"
},
{
teacherName: "Mike"
}
]
];
const output = arrayObject.flat();
console.log(output);
[
{ Name: 'John' },
{ countryName: 'US' },
{ subjectName: 'JavaScript' },
{ teacherName: 'Mike' }
]
Flattening Multiple Levels
For deeply nested arrays, specify the depth parameter:
const deepNested = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
// Flatten one level
console.log("One level:", deepNested.flat());
// Flatten two levels
console.log("Two levels:", deepNested.flat(2));
// Flatten all levels
console.log("All levels:", deepNested.flat(Infinity));
One level: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ] Two levels: [ 1, 2, 3, 4, 5, 6, 7, 8 ] All levels: [ 1, 2, 3, 4, 5, 6, 7, 8 ]
Alternative Methods
You can also use spread operator with concat() for single-level flattening:
const nestedArray = [[1, 2], [3, 4], [5, 6]];
// Using spread operator and concat
const flattened = [].concat(...nestedArray);
console.log("Using spread + concat:", flattened);
// Using reduce
const reduced = nestedArray.reduce((acc, val) => acc.concat(val), []);
console.log("Using reduce:", reduced);
Using spread + concat: [ 1, 2, 3, 4, 5, 6 ] Using reduce: [ 1, 2, 3, 4, 5, 6 ]
Conclusion
The flat() method is the most straightforward way to flatten nested arrays in JavaScript. Use the depth parameter for multi-level nesting, or Infinity to flatten completely.
