This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
var newArray = arr.flat([depth]);
depth Optional
A new array with the sub-array elements concatenated into it.
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6]
The flat method removes empty slots in arrays:
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
reduce and concat
var arr1 = [1, 2, [3, 4]]; arr1.flat(); //to flat single level array arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4] //or const flatSingle = arr => [].concat(...arr);
//to enable deep level flatten use recursion with reduce and concat
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]
//non recursive flatten deep using a stack
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
// pop value from stack
const next = stack.pop();
if (Array.isArray(next)) {
// push back array items, won't modify the original input
stack.push(...next);
} else {
res.push(next);
}
}
//reverse to restore input order
return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
| Specification | Status | Comment |
|---|---|---|
Array.prototype.flat proposal | Candidate (3) |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | 69 | No | 62 | No | 56 | 12 |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | 69 | 69 | No | 62 | 56 | 12 | No |
| Server | |
|---|---|
| Node.js | |
| Basic support | No |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat