It was always complicated to flatten an array in #JavaScript. Not anymore! ES2019 introduced a new method that flattens arrays. And there’s a “depth” parameter, so you can pass in ANY levels of nesting. AMAZING
const nested = [ ['📦', '📦'], ['📦']];
const flattened = nested.flat();
console.log(flattened);
// ['📦', '📦', '📦']
depth
parameterHere’s the syntax for this method:
array.flat(<depth>);
By default, flat()
will only flatten one layer deep. In other words, depth
is 1
.
array.flat();
// Same as
array.flat(1);
The great thing is that this method also works beyond 1 level deep. You simply have to set the appropriate depth
parameter to flatten deeper nested arrays.
const twoLevelsDeep = [[1, [2, 2], 1]];
// depth = 1
twoLevelsDeep.flat()
// [1, [2, 2], 1]
// depth = 2
twoLevelsDeep.flat()
// [1, 2, 2, 1]
Let’s say, you want to go infinitely deep. Not a problem, we can do that too. Just pass Infinity
.
const veryDeep = [[1, [2, 2, [3,[4,[5,[6]]]]], 1]];
veryDeep.flat(Infinity);
// [1, 2, 2, 3, 4, 5, 6, 1]
One other cool thing that flat()
can do is remove empty slots in an array.
const missingNumbers = [1, ,3, ,5];
missingNumbers.flat();
// [1, 3, 5];
flat
is a super new feature introduced in ES2019, so forget Internet Explorer or Edge. But no surprise there 😅
Since support is not great. Here are some alternative solutions.
Here is a ES6 solution. This only work for one level nested array.
const oneLevelDeep = [ [1, 2], [3]];
const flattened = [].concat(...oneLevelDeep);
// [1, 2, 3,]
Here’s one for older browser and pre ES6. Again, this only works for one level nested array.
const oneLevelDeep = [ [1, 2], [3]];
const flattened = [].concat.apply([], oneLevelDeep);
// [1, 2, 3,]
For arrays with deeper nesting, you can use recursion. Here’s the solution from MDN web docs:
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
Got any interesting use cases of Array.flat()?
// Please write a function to search for 213
function search(needle, haystack) {}
const haystack =[1, 4, [5,6,7, [8, 18, [34,177,[98,[210,[213]]]]]]];
const needle = 213;
#javascript