Updated April 1, 2023
Introduction to JavaScript Flatten Array
Flatten means the array which is nested to some level of depth. In Javascript, arrays can be nested with any depth, these arrays can be reformed into a single array, i.e. creating a new array with all the sub-array elements concatenated up to specified depth.
Syntax:
var flatten_array = arr.flat([depth]);
Parameters of JavaScript Flatten Array
Below are the Parameters of JavaScript Flatten Array:
- [depth]: depth specifies how deep the nested array structure is and which should be flattened. By default, depth will be 1.
- Returns new array according to depth specified with sub-array elements concatenated.
- flat() is not yet a part of ECMAScript standard, it is an inbuilt function in Underscore.js library of javascript used to flatten nested array, resultant array will be flattened completely i.e. no depth
Examples of JavaScript Flatten Array
Below are the examples of JavaScript Flatten Array:
Example #1
Code:
const array = [10, 25, [32, 41]];
array.flat();
console.log(array.flat());
Output:
Here, array has value nested inside, .flat() is a function used to break down the nested values and concatenate it to the other values. As there are no parameters passes to flat(), depth is taken as 1.
Example #2
Code:
const array_string = [['Karthick', 45], ['Anusha', 34, ['Keerthi', [24], 56]]];
console.log('flatten by depth 1:', array_string.flat());
document.write('<br/>');
console.log('flatten by depth 2:', array_string.flat(2));
document.write('<br/>');
console.log('flatten by depth 3:', array_string.flat(3));
Output:
Here, array consists of various data types, with depth 1:
Example #3
Infinity nested arrays.
Code:
const array_string = [1,2,[3,[4,[5,6,7,[8],9]]]];
console.log('flatten by depth infinity:', array_string.flat(Infinity));
Output:
Infinity depth refers to endless depths inside an array can be flattened.
Example #4
Flattening array holes i.e. a partially empty array can also be flattened here.
Code:
const array_string = [1,2, ,4, 5, , 8];
console.log('flatten by depth infinity:', array_string.flat());
Output:
Empty values are found in the above array_string, but the array is flattened and empty arrays are removed from the array_string.
In javascript, ES2019 introduced flat and flatMap array protoypes, both are used to flatten array. Fairly new browsers support the above but the old browsers do not, hence to support this we use Babel. Instead of using babel to reframe code to lower version of ES, we can make use of flatten(), flattenDeep() and flattenDepth() functions provided by Lodash.
We need to import whole library of Lodash, these functions can be used individually using the packages.
Example #5
Using flatMap(), It maps each value to a new value, and resulting array is flatten to a depty of maximum 1.
Code:
const employee = ['Karthick', 'Saideep', 'Anusha', 'Keerthi'];
const client = ['Westpac', 'Sysco', 'Telco', 'Metlife'];
const mappedOnly = employee.map((employee, index) => [employee, client[index]]);
const mappedAndFlatten = employee.flatMap((employee, index) => [employee, client[index]]);
console.log(mappedOnly);
// [['Karthick', 'Westpac'], ['Saideep', 'Sysco'], ['Anusha', 'Telco'], ['Keerthi', 'Metlife']]
console.log(mappedAndFlatten);
Output:
flatMap() is a combination of map() and flat(), useful when calling function that returns an array in map() with resulting array being flat.
Let us see some of the ways to flatten multi dimensional array.
Example #6
Code:
var myArray = [[16, 62],[35, 45, 57], [66, 7, 88]];
var flattenedArray = [].concat.apply([], myArray);
console.log(flattenedArray);
Output:
Here, without using .flat() function, multi dimensional array has been flattened.
Example #7
Code:
var myArray = [[41, 24],[33, 42, 56], [66, 72, 82]];
var flattened_Array = [];
for (var i = 0; i < myArray.length; ++i) {
for (var j = 0; j < myArray[i].length; ++j)
flattened_Array.push(myArray[i][j]);
}
console.log(flattened_Array);
Output:
Using simple for loop, multi-dimensional arrays can also be flattened.
Example #8
Using ES6 spread operator, it works only with array with depth 1
Code:
var myArray = [[41, 24],[33, 42, 56], [66, 72, 82]];
var flattened_array = [].concat(...myArray);
console.log(flattened_array);
Output:
Let us see the iterative of flattening the array.
Example #9
Code:
function flatten(arr) {
var flattened_array = [];
while(arr.length) {
var value = arr.shift();
if(Array.isArray(value)) {
// this line preserve the order
arr = value.concat(arr);
} else {
flattened_array.push(value);
}
}
console.log(flattened_array);
}
flatten([13,[23,[38]],[4, 7, 90]]);
Output:
Example #10
Code:
let initialArray = [[0, 1], [2, 3]];
let flattenedArray = initialArray.reduce((a, b) => {
console.log(a.concat(b));
});
Output:
Whenever libraries add some additional data or array wraps, user likes to get rid of it because it is sendas JSON to server as code might crash. In such cases, flattening is useful as it saves time. Flattened data is easier to read than to handle nested arrays/ data.
Using generator function, For deep flattening of a javascript array, we can use a generator function, i. e. Array.isArray()
Example #11
Code:
function* flatten(array)
{
for (const val of array) {
Array.isArray(val) ? yield* flatten(val) : yield val;
}
}
const array = [[16,21],[39,[41,[60]]]];
const flattened_array = [...flatten(array)];
console.log(flattened_array);
Output:
Conclusion
By this we conclude this article on ‘Javascript Flatten Array’. We have seen what Javascript flatten array mean, its various examples provided with different depths for function flat(), generator function, spread operator, reduce, iteration, using for loop and so on. We have also seen why this flattening of array is needed in Javascript and its uses. There are many other ways of flattening the nested array to single dimension array using Lodash, flatten(), flattenDeep() and flattenDepth() which work individually using their packages.
Recommended Articles
This is a guide to JavaScript Flatten Array. Here we discuss the Introduction to JavaScript Flatten Array and its Parameters along with Examples and Code Implementation. You can also go through our other suggested articles to learn more –