Introduction
Flattening an array is a process of decreasing the dimensionality of the Array. One can use many inbuilt methods to reduce the dimension of a multidimensional array. For example,
arr=[[1, 2],[3, 4],[5, 6],[7,8]] is a 2-D array. By flattening the array, we can turn it into a 1-D array [1, 2, 3, 4, 5, 6, 7, 8]
We will also look into how to flatten an array without using any inbuilt functions.
Different methods to flatten an array
There are many ways to flatten a multidimensional array.
Using built-in methods
Use of spread (...) operator
In ES6, one can flatten an array by using the spread operator.
function flatten(arr) {
return [].concat(...arr);
}
var arr = [4, 5, [6, 7]];
console.log(flatten(arr))
Output
[ 4, 5, 6, 7 ]
Using .apply(_) and .concat(_) method
one can use these two methods for flattening an array. We pass two arguments to the apply(_) method - an empty array and the array we want to flatten(arr), then concatenate all the elements(sub-arrays) passed into an empty array. Thus obtaining a 1-dimensional array.
function flatten(arr) {
return [].concat.apply([], arr);
}
var arr = [4, 5, [6, 7]];
console.log(flatten(arr))
Output
[ 4, 5, 6, 7 ]
Using .toString(_) and .split(_) method
First, the array will be converted into a string, splitting it by commas. Then every character of the string will be mapped to a number again.
var arr = [4,[5,6,[7,8],9]];
const flatten = arr.toString().split(',').map(Number)
console.log(flatten);
Output
[ 4, 5, 6, 7, 8, 9 ]
Use of flat(_) method
We can flatten an array using flat() method (introduced in ES2019) by specifying the depth of the array. The depth of an array is calculated as the number of levels of the bracket pairs in the array. The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. The depth parameter is optional, and when no depth is specified, a depth of 1 is considered by default.
let arr = [4,[5,6,[7,8],9]];
console.log(arr.flat(2));
Output
[ 4, 5, 6, 7, 8, 9 ]
Without using built-in methods
var arr = [4,[5,6,[7,8],9]];
function flatten(arr)
{
//here we will store final result
let ans = [];
let main = arr, first;
//looping
while(main.length > 0)
{
first = main[0];
if(Array.isArray(first)) {
Array.prototype.splice.apply(main, [0, 1].concat(first));
} else {
ans.push(first);
main.splice(0, 1);
}
}
return ans;
}
console.log(flatten(arr));
Output
[ 4, 5, 6, 7, 8, 9 ]